<?php
//
// Scheduled Reporting Component
// Copyright (c) 2011-2017 Nagios Enterprises, LLC. All rights reserved.
//

require_once(dirname(__FILE__) . '/../../common.inc.php');

// Initialization stuff
pre_init();
init_session();

// Grab GET or POST variables and check pre-reqs
grab_request_vars();
check_prereqs();
check_authentication(false);

route_request();

function route_request()
{
    global $request;

    $id = grab_request_var("id", "");
    $url = grab_request_var("url", "");
    $wurl = grab_request_var("wurl", "");
    $type = grab_request_var("type", "");
    $delete = grab_request_var("delete", "");
    $update = grab_request_var("update", "");
    $edit = grab_request_var("edit", "");
    $visit = grab_request_var("visit", "");
    $send = grab_request_var("send", "");
    $getajaxdata = grab_request_var('getajaxdata', '');

    // Highjack for the actual template changing
    $action = grab_request_var("action", "");
    if ($action == "changetemplate") {
        do_change_template();
    }

    if ($delete == 1)
        do_delete();
    else if ($update == 1)
        do_update();
    else if ($visit == 1)
        do_visit();
    else if ($send == 1)
        do_send();
    else if ($edit == 1 || $url != "" || $type == "page")
        show_edit();
    else if ($getajaxdata == 1)
        get_sr_ajax_data();
    else
        show_reports();
}

// Change the template to whatever we want it to be
function do_change_template()
{
    global $request;

    // Check session
    check_nagios_session_protector();

    // Garb the new template
    $template = grab_request_var("email_template_text", "");

    // Save new template
    $userid = get_user_id($_SESSION['username']);
    set_user_meta($userid, "scheduled_report_email_template", $template); // Being escaped in function
    flash_message(_("Updated your email template."));

    show_reports();
}

function show_reports($error = false, $msg = "")
{
    $delete = grab_request_var('delete', '');
    $update = grab_request_var('update', '');

    $title = _("My Scheduled Reports");
    do_page(array("page_title" => $title, "enterprise" => true), true);

    if (!empty($delete) || !empty($update)) {
    ?>
    <script>
    $(document).ready(function() {
        if ($('#leftnav div.menusectiontitle[data-id="menu-reports-scheduledreportings"]', window.parent.document).length) {
            $.get('<?php echo get_base_url(); ?>includes/components/scheduledreporting/schedulereport.php', { 'getajaxdata': 1 }, function(data) {
                $('#leftnav div.menusectiontitle[data-id="menu-reports-scheduledreportings"]', window.parent.document).eq(0).parent().find('ul.menusection').html(data.html);
                $('#leftnav div.menusectiontitle[data-id="menu-reports-scheduledreportings"] span.num', window.parent.document)[0].innerHTML = '('+data.count+')';
            }, 'json');
        }
    });
    </script>
    <?php } ?>

    <h1><?php echo $title; ?></h1>

    <?php
    display_message($error, false, $msg);

    // Enterprise Feature Neatness
    // ** THIS FILE NEEDS TO BE ENCRYPTED **
    $eo_output = "";

    // Do actual enterprise only check
    make_enterprise_only_feature();

    // Enterprise Edition message
    if (get_theme() != 'xi5') {
        echo enterprise_message();
    }
    ?>

    <script>
    $(document).ready(function () {
        $("#tabs").tabs().show();
        $("#reset-email-template").click(function () {
            var text = "This scheduled report was automatically generated by Nagios XI and sent to you as requested by [username] ([name]).\n\n[custommessage]\n\nYou can directly access this report at:\n[reporturl]\n\nAccess Nagios XI at:\n[nagiosxiurl]";
            $("#email-template-text").val(text);
        });
    });
    </script>

    <div id="tabs" class="hide">
        <ul>
            <li><a href="#reports"><?php echo $title; ?></a></li>
            <li><a href="#email-template"><?php echo _("Report Email Template"); ?></a></li>
        </ul>
        <div id="reports">

            <p>
                <?php echo _("Your scheduled reports are listed here."); ?>
            </p>

            <table class="table table-condensed table-auto-width table-striped" style="min-width: 50%;">
                <thead>
                    <tr>
                        <th><?php echo _("Name"); ?></th>
                        <th><?php echo _("Subject"); ?></th>
                        <th><?php echo _("Type"); ?></th>
                        <th><?php echo _("Frequency"); ?></th>
                        <th><?php echo _("Recipients"); ?></th>
                        <th style="width: 90px; text-align: center;"><?php echo _("Actions"); ?></th>
                    </tr>
                </thead>
                <tbody>

                <?php

                // Grab menu items
                $scheduled_reports = scheduledreporting_component_get_reports();
                //~ print_r($scheduled_reports);
                if (count($scheduled_reports) == 0) {
                    echo "<tr><td colspan='6'>" . _('You have not scheduled any reports') . ".</td></tr>";
                } else {
                    foreach ($scheduled_reports as $id => $sr) {

                        $type = grab_array_var($sr, "type", "");
                        $subject = grab_array_var($sr, "subject", "");
                        $frequency = $sr['frequency'];
                        $sched = grab_array_var($sr, "schedule", array());

                        $hour = grab_array_var($sched, "hour", "");
                        $minute = grab_array_var($sched, "minute", "");
                        $ampm = grab_array_var($sched, "ampm", "");
                        $dayofweek = grab_array_var($sched, "dayofweek", "");
                        $dayofmonth = grab_array_var($sched, "dayofmonth", "");

                        if (empty($type)) { $type = _('Report'); }

                        $days = array(
                            0 => _('Sunday'),
                            1 => _('Monday'),
                            2 => _('Tuesday'),
                            3 => _('Wednesday'),
                            4 => _('Thursday'),
                            5 => _('Friday'),
                            6 => _('Saturday'),
                        );

                        if ($frequency == "Disabled")
                            $fstr = "";
                        else if ($frequency == "Once")
                            $fstr = "(" . _("Pending") . ")";
                        else
                            $fstr = $hour . ":" . $minute . " " . $ampm;
                        if ($frequency == "Weekly")
                            $fstr .= " " . $days[$dayofweek];
                        else if ($frequency == "Monthly")
                            $fstr .= ", " . _("Day") . " " . $dayofmonth;

                        echo "<tr>
                <td><a href='?edit=1&id=" . urlencode($id) . "&nsp=" . get_nagios_session_protector_id() . "'>" . encode_form_val($sr['name']) . "</a></td>
                <td>" . encode_form_val($sr['subject']) . "</td>
                <td>" . ucfirst(encode_form_val($type)) . "</td>
                <td>" . encode_form_val($frequency) . " @ " . $fstr . "</td>
                <td>" . str_replace(",", ", ", encode_form_val($sr['recipients'])) . "</td>
                <td style='width: 90px; text-align: center;'>
                ";
                        if ($frequency != "Once")
                            echo "<a href='?edit=1&id=" . urlencode($id) . "&nsp=" . get_nagios_session_protector_id() . "'><img src='" . get_icon_url("pencil.png") . "' alt='"._('Edit')."' title='"._('Edit')."' class='tt-bind'></a>&nbsp;";

                        echo "<a href='?delete=1&id=" . urlencode($id) . "&nsp=" . get_nagios_session_protector_id() . "'><img src='" . get_icon_url("cross.png") . "' alt='"._('Delete')."' title='"._('Delete')."' class='tt-bind'></a>";
                        if ($frequency != "Once")
                            echo "
                    <a href='?visit=1&id=" . urlencode($id) . "&nsp=" . get_nagios_session_protector_id() . "'><img src='" . get_icon_url("b_next.png") . "' alt='"._('View')."' title='"._('View')."' class='tt-bind'></a>
                    <a href='?send=1&id=" . urlencode($id) . "&nsp=" . get_nagios_session_protector_id() . "'><img src='" . get_icon_url("sendemail.png") . "' alt='"._('Send Now')."' title='"._('Send Now')."' class='tt-bind'></a>
                    ";
                        echo "
                </td>
                </tr>";
                    }
                }
                ?>
                </tbody>
            </table>
        </div>
        <div id="email-template">

            <form method="post" action="schedulereport.php">
                <input type="hidden" name="action" value="changetemplate">
                <?php echo get_nagios_session_protector(); ?>

                <p><?php echo _("Edit the email you will get when you recieve a scheduled report."); ?></p>

                <h4><?php echo _("Email Body"); ?></h4>

                <div>
                    <textarea name="email_template_text" id="email-template-text" class="form-control" style="min-width: 800px; width: 70%; height: 300px;"><?php
                        // Grab the users email template
                        $userid = get_user_id($_SESSION['username']);
                        $template = get_user_meta($userid, "scheduled_report_email_template");
                        if ($template == NULL) {
                            // Display the default email template
                            echo "This scheduled report was automatically generated by Nagios XI and sent to you as requested by [username] ([name]).\n\n[custommessage]\n\nYou can directly access this report at:\n[reporturl]\n\nAccess Nagios XI at:\n[nagiosxiurl]";
                        } else {
                            echo encode_form_val($template);
                        }
                        ?></textarea>
                </div>
                <div style="margin: 10px 0 30px 0; min-width: 800px; width: 70%;">
                    <div style="float: left;"><?php echo _("Useable macros"); ?>: [username], [name], [reporturl],
                        [nagiosxiurl], [custommessage]
                    </div>
                    <div style="float: right;">
                        <a href="#" id="reset-email-template" class="btn btn-xs btn-info"><?php echo _("Reset template to default"); ?></a>
                    </div>
                    <div style="clear: both;"></div>
                </div>
                <div>
                    <button class="btn btn-sm btn-primary"><?php echo _("Save Settings"); ?></button>
                </div>
            </form>

        </div>

    </div>

    <?php
    do_page_end(true);
    exit();
}

function do_send($theid = -1, $sendonce = false)
{
    // Check session
    check_nagios_session_protector();

    // Grab variables
    $id = grab_request_var("id", -1);

    // Overrides
    if ($theid != -1) {
        $id = $theid;
    }

    // Get report
    $report = scheduledreporting_component_get_report_id($id);

    $errmsg = array();
    $errors = 0;

    // Check for errors
    if ($id == -1) {
        $errmsg[$errors++] = _("Invalid report ID.");
    } else if ($report == null) {
        $errmsg[$errors++] = _("Invalid report array.");
    }

    // Handle errors
    if ($errors > 0) {
        show_reports(true, $errmsg);
    }

    $cmdline = scheduledreporting_component_get_cmdline($id);

    exec($cmdline, $output, $bool);
    scheduled_reporting_component_log("\n\nCMD: $cmdline\nRET: $bool\nOUTPUT: " . implode("\n", $output));

    $msg = _("Report is being sent.");
    
    // Handle error
    if ($bool > 0) {
        $msg = _("Report failed to send.") . " \n" . implode("\n", $output);
    }

    if ($sendonce === true && $bool === 0) {

        $url = $report['url'];

        // check for nagvis url [tps:7367] - bh
        $is_nagios_url = true;
        $full_url_pattern = '/http[s]?:\/\/.*/';
        if (preg_match($full_url_pattern, $url) === 1)
            $is_nagios_url = false;

        if ($is_nagios_url) {
            $url = str_replace(get_base_uri(false), '', $url);
            $url = get_base_uri(false).$url;
            $url = str_replace('//', '/', $url);
        }

        header("Location: $url");
    } else {
        show_reports($bool, $msg);
    }
}

function do_visit()
{
    // Check session
    check_nagios_session_protector();

    // Grab variables
    $id = grab_request_var("id", -1);

    // Get report
    $report = scheduledreporting_component_get_report_id($id);

    $errmsg = array();
    $errors = 0;

    // Check for errors
    if ($id == -1) {
        $errmsg[$errors++] = _("Invalid report ID.");
    } else if ($report == null) {
        $errmsg[$errors++] = _("Invalid report array.");
    }

    // Handle errors
    if ($errors > 0) {
        show_reports(true, $errmsg);
    }

    $url = scheduledreporting_component_get_scheduled_report_url($id);

    // Redirect
    header("Location: " . $url);
    exit();
}


function do_delete()
{
    check_nagios_session_protector();

    // grab variables
    $id = grab_request_var("id", -1);

    $errmsg = array();
    $errors = 0;

    // check for errors
    if (in_demo_mode() == true)
        $errmsg[$errors++] = _("Changes are disabled while in demo mode.");
    if ($id == -1)
        $errmsg[$errors++] = _("Invalid report.");

    // handle errors
    if ($errors > 0)
        show_reports(true, $errmsg);

    // delete the report
    scheduledreporting_component_delete_report($id);

    show_reports(false, _("Report deleted."));
}


function do_update()
{
    global $request;

    // Grab variables
    $id = grab_request_var("id", -1);
    $name = grab_request_var("name", "New Report");
    $type = grab_request_var("type", "");
    $url = grab_request_var("url", "");
    $frequency = grab_request_var("frequency", "");
    $hour = grab_request_var("hour", "09");
    $minute = grab_request_var("minute", "00");
    $ampm = grab_request_var("ampm", "AM");
    $dayofweek = grab_request_var("dayofweek", "");
    $dayofmonth = grab_request_var("dayofmonth", "");
    $recipients = grab_request_var("recipients", "");
    $subject = grab_request_var("subject", "");
    $body = grab_request_var("body", "");
    $attachments = grab_request_var("attachments", array());
    $sendonce = grab_request_var("sendonce", 0);
    $dontdisplay = grab_request_var('dontdisplay', 0);

    $userid = 0;
    $length = 0;
    if (is_admin()) {
        $userid = intval(grab_request_var('userid', 0));
        $length = intval(grab_request_var('length'), 10);
    }

    $full_url_pattern = '/http[s]?:\/\/.*/';
    if (preg_match($full_url_pattern, $url) !== 1) 
        $url = str_replace(get_base_uri(false), '', $url);

    // User pressed the cancel button
    if (isset($request["cancelButton"])) {
        if ($id == -1) {
            $url = get_base_url() . $url;
            header("Location: $url");
        } else {
            header("Location: schedulereport.php");
        }    
        exit();
    }

    // Check session
    check_nagios_session_protector();

    $errmsg = array();
    $errors = 0;

    // Check for errors
    if (in_demo_mode() == true)
        $errmsg[$errors++] = _("Changes are disabled while in demo mode.");
    if (empty($url))
        $errmsg[$errors++] = _("Invalid report URL.");
    if (empty($name))
        $errmsg[$errors++] = _("No report name specified.");
    if (empty($recipients))
        $errmsg[$errors++] = _("No recipients specified.");
    if ($frequency != "Once" && enterprise_features_enabled() == false) {
        $errmsg[$errors++] = _("Scheduled reports are only available in the Enterprise Edition.");
    }

    // Handle errors
    if ($errors > 0)
        show_edit(true, $errmsg);

    $newreport = array(
        "name" => $name,
        "type" => $type,
        "url" => $url,
        "dontdisplay" => $dontdisplay,
        "recipients" => $recipients,
        "frequency" => $frequency,
        "subject" => $subject,
        "body" => $body,
        "schedule" => array(
            "hour" => $hour,
            "minute" => $minute,
            "ampm" => $ampm,
            "dayofweek" => $dayofweek,
            "dayofmonth" => $dayofmonth
        ),
        "attachments" => $attachments
    );

    $reports = scheduledreporting_component_get_reports($userid);

    // Create a new report id if necessary
    if ($id == -1) {
        $add = true;
        do {
            $id = random_string(12);
        } while (array_key_exists($id, $reports));
    } else {
        $add = false;
    }

    // Add or Update report
    $reports[$id] = $newreport;

    scheduledreporting_component_save_reports($reports, $userid);
    if ($frequency == "Disabled") {
        scheduledreporting_component_delete_cron($id, $userid);
    } else if ($frequency != "Once") {
        scheduledreporting_component_update_cron($id, $userid);
    }

    // Redirect if we are doing this as an admin
    if (is_admin() && $userid) {
        flash_message(_("Successfully updated report."));
        header("Location: manage.php?user_id=".$userid."&length=".$length);
        exit();
    }

    if ($frequency == "Once" || $sendonce == 1) {
        do_send($id, true);
    } else {
        if ($add == true) {
            $msg = _("Report scheduled.");
        } else {
            $msg = _("Scheduled report updated.");
        }

        show_reports(false, $msg);
    }
}

function show_edit($error = false, $msg = "")
{

    // defaults
    $id = -1;
    $name = "";
    $type = "";
    $url = "";
    $wurl = "";
    $frequency = "Daily";
    $recipients = "";
    $subject = "";
    $body = "";
    $sendonce = 0;
    $dontdisplay = "";
    $userid = 0;
    $length = 0;

    $hour = "09";
    $minute = "00";
    $ampm = "AM";
    $dayofweek = "1";
    $dayofmonth = "1";

    $sendonce = 0;

    $attachments = null;

    // grab id
    $id = grab_request_var("id", -1);
    // grab type (report or page)
    $type = grab_request_var("type", "");

    if ($id == -1) {
        $add = true;
        if ($type == "page")
            $title = _("Schedule New Page");
        else
            $title = _("Schedule New Report");
    } else {
        $add = false;

        // get existing report
        $userid = 0;
        if (is_admin()) {
            $userid = intval(grab_request_var('userid', 0));
            $length = intval(grab_request_var('length', 10));
        }
        $sr = scheduledreporting_component_get_report_id($id, $userid);

        // vars default to saved values
        $name = grab_array_var($sr, "name", "");
        $type = grab_array_var($sr, "type", "");
        $url = grab_array_var($sr, "url", "");
        $frequency = grab_array_var($sr, "frequency", "");
        $recipients = grab_array_var($sr, "recipients", "");
        $subject = grab_array_var($sr, "subject", "");
        $body = grab_array_var($sr, "body", "");

        $sched = grab_array_var($sr, "schedule", array());
        $hour = grab_array_var($sched, "hour", $hour);
        $minute = grab_array_var($sched, "minute", $minute);
        $ampm = grab_array_var($sched, "ampm", $ampm);
        $dayofweek = grab_array_var($sched, "dayofweek", $dayofweek);
        $dayofmonth = grab_array_var($sched, "dayofmonth", $dayofmonth);

        $dontdisplay = grab_array_var($sr, 'dontdisplay', 0);

        $attachments = grab_array_var($sr, "attachments", $attachments);

        if ($type == "page")
            $title = _("Edit Scheduled Page");
        else
            $title = _("Edit Scheduled Report");
    }

    // grab request variables
    $name = grab_request_var("name", $name);
    $type = grab_request_var("type", $type);
    $url = grab_request_var("url", $url);
    $wurl = grab_request_var("wurl", $wurl);
    $xi_basedir = grab_request_var("xi_basedir", 1);
    $frequency = grab_request_var("frequency", $frequency);
    $recipients = grab_request_var("recipients", $recipients);
    $subject = grab_request_var("subject", $subject);
    $body = grab_request_var("body", $body);

    $hour = grab_request_var("hour", $hour);
    $minute = grab_request_var("minute", $minute);
    $ampm = grab_request_var("ampm", $ampm);
    $dayofweek = grab_request_var("dayofweek", $dayofweek);
    $dayofmonth = grab_request_var("dayofmonth", $dayofmonth);

    $attachments = grab_request_var("attachments", $attachments);

    $sendonce = grab_request_var("sendonce", 0);

    $dontdisplay = grab_request_var('dontdisplay', $dontdisplay);

    if ($add == true && $subject == "")
        $subject = $name;

    if ($add == true && $recipients == "")
        $recipients = get_user_attr(0, "email");

    if ($add == true && $sendonce == 1) {
        $frequency = "Once";
        if ($type == "page")
            $title = _("Email Page");
        else
            $title = _("Email Report");
    }

    // check if null (old report pages)
    if (is_null($attachments)) {
        $attachments = array('pdf' => 'on');
    }

    // fix page urls...
    if ($add == true && $type == "page" && $url == "") {
        $newurl = "";
        $parsed_url = parse_url($wurl);
        $pos = strpos($parsed_url['path'], get_base_uri(false));
        if ($pos === FALSE)
            $newurl = "";
        else {
            $qs = (!empty($parsed_url['query'])) ? '?' . $parsed_url['query'] : '';
            $newurl = substr($parsed_url['path'], $pos + 10) . $qs;
        }
        //    echo "NEWURL: $newurl<BR>";

        // Hack for capacity planning
        //if (strpos($parsed_url['path'], "capacityplanning.php") !== FALSE) {
        //    $newurl .= '#' . $parsed_url['fragment'] . "&pdf=1";
        //}

        $url = $newurl;
    }

    // get options for this report
    $sro = scheduledreporting_component_get_report_options($url);

    do_page(array("page_title" => _($title), "enterprise" => true), true);
?>

    <h1><?php echo $title; ?></h1>

    <?php display_message($error, false, $msg); ?>

    <?php
    //echo "SENDONCE: '$sendonce'<BR>";
    //echo "FREQ: '$frequency'<BR>";
    // Enterprise Edition message if not sending immediately
    if ($sendonce != 1 || ($sendonce == 1 && $frequency != "Once")) {
        // Enterprise Feature Neatness
        // ** THIS FILE NEEDS TO BE ENCRYPTED **
        $eo_output = "";

        // Do actual enterprise only check
        make_enterprise_only_feature();

        if (get_theme() != 'xi5') {
            echo enterprise_message();
        }
    }
    ?>

    <form id="manageReportForm" method="post" action="<?php echo encode_form_val($_SERVER['PHP_SELF']); ?>">

    <?php echo get_nagios_session_protector(); ?>
    <input type="hidden" name="update" value="1">
    <input type="hidden" name="id" value="<?php echo encode_form_val($id); ?>">
    <input type="hidden" name="type" value="<?php echo encode_form_val($type); ?>">
    <input type="hidden" name="url" value="<?php echo encode_form_val($url); ?>">
    <input type="hidden" name="wurl" value="<?php echo encode_form_val($wurl); ?>">
    <input type="hidden" name="userid" value="<?php echo $userid; ?>">
    <input type="hidden" name="length" value="<?php echo $length; ?>">
    <input type="hidden" name="sendonce" value="<?php echo encode_form_val($sendonce); ?>">

    <?php
    if ($add == true) {
        if ($sendonce == 1) {
            ?>
            <p>
                <?php echo _("Use this form to send the selected report to one or more recipients you define.  You may also schedule the report to be sent to the recipients on a regular basis if you choose."); ?>
            </p>
        <?php
        } else {
            ?>
            <p>
                <?php echo _("Use this form to create a new scheduled report that is sent to one or more recipients you define."); ?>
            </p>
        <?php
        }
    } else {
        ?>
        <p>
            <?php echo _("Use this form to modify an existing scheduled report."); ?>
        </p>
    <?php
    }
    ?>

    <script type='text/javascript'>
        $(document).ready(function () {
            showTimeOpts();
        });
        function showTimeOpts() {
            var opt = $('#select_frequency').val();
            //hide all options and then decide what to show

            switch (opt) {
                case 'Daily':
                    $('#dayofweek-div').hide();
                    $('#dayofmonth-div').hide();
                    $('#time-div').show();
                    $('#updateButton').html('<?php echo _("Save"); ?>');
                    break;
                case 'Weekly':
                    $('#dayofmonth-div').hide();
                    $('#time-div').show();
                    $('#dayofweek-div').show();
                    $('#updateButton').html('<?php echo _("Save"); ?>');
                    break;
                case 'Monthly':
                    $('#dayofweek-div').hide();
                    $('#time-div').show();
                    $('#dayofmonth-div').show();
                    $('#updateButton').html('<?php echo _("Save"); ?>');
                    break;
                case 'Once':
                    $('#time-div').hide();
                    $('#dayofweek-div').hide();
                    $('#dayofmonth-div').hide();
                    $('#updateButton').html('<?php echo _("Send"); ?>');
                    break;
                default:
                    $('#time-div').hide();
                    $('#dayofweek-div').hide();
                    $('#dayofmonth-div').hide();
                    $('#updateButton').html('<?php echo _("Save"); ?>');
                    break;
            }
        }
    </script>

    <table class="table table-condensed table-no-border table-auto-width">

    <?php
    if ($type == "page") {
        ?>
        <tr>
            <td class="vt">
                <label for="nameBox"><?php echo _("Page URL"); ?>:</label
            </td>
            <td>
                <?php
                $base_url = ($xi_basedir == 1 ? get_base_url() : "");
                ?>
                <a href="<?php echo htmlspecialchars($base_url . $url, ENT_QUOTES); ?>" target="_blank"><?php echo htmlspecialchars($url, ENT_QUOTES); ?></a>
                <div class="subtext">
                    <?php 
                        if ($xi_basedir == 1) {
                            echo _("The relative URL of the page to deliver as a scheduled report"); 
                        } else {
                            echo _("The URL of the page to deliver as a scheduled report"); 
                        }
                    ?>.
                </div>
            </td>
        </tr>
        <?php
        if ($wurl != "") {
            ?>
            <tr>
                <td class="vt">
                    <label for="nameBox"><?php echo _("Original URL"); ?>:</label>
                </td>
                <td>
                    <a href="<?php echo htmlspecialchars($wurl, ENT_QUOTES); ?>" target="_blank"><?php echo htmlspecialchars($wurl, ENT_QUOTES); ?></a>
                </td>
            </tr>
        <?php
        }
    }
    ?>

    <tr>
        <td class="vt">
            <label for="nameBox"><?php echo _("Report Name"); ?>:</label>
        </td>
        <td>
            <input type="text" size="40" name="name" id="nameBox" value="<?php echo encode_form_val($name); ?>" class="textfield form-control">
            <div class="subtext"><?php echo _("The name you want to use for this report."); ?></div>
        </td>
    </tr>

    <tr>
        <td class="vt">
            <label><?php echo _("Schedule"); ?>:</label><br class="nobr"/>
        </td>
        <td>
            <div>
                <span style="margin-right: 8px;">
                    <?php echo _("Frequency"); ?>:
                    <select name='frequency' id='select_frequency' class="form-control" onchange='showTimeOpts()'>
                        <?php
                        $enable_once = false;
                        if ($add == true && ($sendonce == 1 || $type == "page"))
                            $enable_once = true;
                        if ($enable_once == true)
                            echo "<option value='Once' " . is_selected($frequency, "Once") . ">" . _("One Time") . "</option>";
                        ?>
                        <option value='Disabled' <?php echo is_selected($frequency, "Disabled"); ?>><?php echo _("Disabled"); ?></option>
                        <option value='Daily' <?php echo is_selected($frequency, "Daily"); ?>><?php echo _("Daily"); ?></option>
                        <option value='Weekly' <?php echo is_selected($frequency, "Weekly"); ?>><?php echo _("Weekly"); ?></option>
                        <option value='Monthly' <?php echo is_selected($frequency, "Monthly"); ?>><?php echo _("Monthly"); ?></option>
                    </select>
                </span>
                <span id="time-div" style="margin-right: 8px;">
                    <?php echo _("Time"); ?>:
                    <select name="hour" class="form-control">
                        <?php
                        for ($x = 1; $x <= 12; $x++) {
                            $nstr = sprintf("%02d", $x);
                            echo "<option value='" . $nstr . "' " . is_selected($hour, $nstr) . ">" . $nstr . "</option>";
                        }
                        ?>
                    </select>:<select name="minute" class="form-control">
                        <?php
                        for ($x = 0; $x < 60; $x++) {
                            $nstr = sprintf("%02d", $x);
                            echo "<option value='" . $nstr . "' " . is_selected($minute, $nstr) . ">" . $nstr . "</option>";
                        }
                        ?>
                    </select>
                    <select name="ampm" class="form-control">
                        <option value="AM" <?php echo is_selected($ampm, "AM"); ?>>AM</option>
                        <option value="PM" <?php echo is_selected($ampm, "PM"); ?>>PM</option>
                    </select>
                </span>
                <span id="dayofweek-div">
                    <?php echo _("Weekday"); ?>:
                    <select name="dayofweek" class="form-control">
                        <?php
                        $days = array(
                            0 => 'Sunday',
                            1 => 'Monday',
                            2 => 'Tuesday',
                            3 => 'Wednesday',
                            4 => 'Thursday',
                            5 => 'Friday',
                            6 => 'Saturday',
                        );
                        foreach ($days as $did => $day) {
                            echo "<option value='" . $did . "' " . is_selected($dayofweek, $did) . ">" . $day . "</option>";
                        }
                        ?>
                    </select>
                </span>
                <span id="dayofmonth-div">
                    <?php echo _("Day of Month"); ?>:
                    <select name="dayofmonth" class="form-control">
                        <?php
                        for ($x = 1; $x <= 31; $x++) {
                            echo "<option value='" . $x . "' " . is_selected($dayofmonth, $x) . ">" . $x . "</option>";
                        }
                        ?>
                    </select>
                </span>
            </div>

            <div class="subtext">
            <?php if ($sendonce == 1) { ?>
                <?php echo _("If you'd like to have the report emailed on a regular basis, specify the schedule here."); ?>
            <?php } else { ?>
                <?php echo _("Specify the schedule you want this report to be emailed."); ?>
            <?php } ?>
            </div>

        </td>
    </tr>
    <tr>
        <td class="vt">
            <label><?php echo _("Attachments"); ?>:</label>
        </td>
        <td>
            <table class="table table-condensed table-auto-width table-no-border">
                <tbody>
                    <?php 
                        foreach ($sro["attachments"] as $aid => $a) {
                            if (!array_key_exists($aid, $attachments))
                                $attachments[$aid] = "";
                            if ($add == true && $error == false) {
                                if ($aid == "pdf")
                                    $attachments[$aid] = "on"; // default pdf to being checked
                            }
                            echo "<tr><td class='checkbox'>";
                            echo "<label><input type='checkbox' name='attachments[" . $aid . "]' " . is_checked($attachments[$aid]) . "> ";
                            echo "<i class='fa fa-14 " . $a["icon"] . "' alt='" . $a["type"] . "' title='" . $a["type"] . "'></i> " . $a["type"] . "</label>";
                            echo "</td></tr>";
                        }
                    ?>
                </tbody>
            </table>
            <div class="subtext">
            <?php if ($type == "page") { ?>
                <?php echo _("The specified page will be rendered and delivered as a PDF."); ?><br><br>
            <?php } else { ?>
                <?php echo _("Select the types of attachment(s) you want in the report."); ?><br><br>
            <?php } ?>
            </div>
        </td>
    </tr>
    <tr>
        <td class="vt">
            <label><?php echo _("Recipients:"); ?></label>
        </td>
        <td>
            <input type="text" size="80" name="recipients" value="<?php echo encode_form_val($recipients); ?>" class="textfield form-control">
            <div class="subtext"><?php echo _("Comma-separated list of email addresses this report should be sent to."); ?></div>
        </td>
    </tr>
    <tr>
        <td class="vt">
            <label><?php echo _("Subject"); ?>:</label>
        </td>
        <td>
            <input type="text" size="50" name="subject" value="<?php echo encode_form_val($subject); ?>" class="textfield form-control">
            <div class="subtext"><?php echo _("The subject that should be used for the report email."); ?></div>
        </td>
    </tr>
    <tr>
        <td class="vt">
            <label><?php echo _("Message"); ?>:</label>
        </td>
        <td>
            <textarea style="width: 40%; min-width: 500px; height: 100px;" wrap="physical" class="form-control" name="body"><?php echo encode_form_val($body); ?></textarea>
            <div class="subtext"><?php echo _("A custom message to be added to the report email."); ?></div>
        </td>
    </tr>

    <?php
    if ($add == true && $sendonce == 1)
        $savebtn = _('Send');
    else
        $savebtn = _('Save');
    ?>

    <tr>
        <td></td>
        <td class="checkbox">
            <label><input type="checkbox" name="dontdisplay" value="1" <?php if ($dontdisplay == 1) { echo 'checked'; } ?>> <?php echo _('Do not show this report in the my scheduled reports menu section.'); ?></label>
        </td>
    </tr>

    </table>

        <div id="formButtons">
            <button type="submit" class="btn btn-sm btn-primary" name="updateButton" id="updateButton"><?php echo $savebtn; ?></button>
            <?php if (!$userid) { ?>
            <button type="submit" class="btn btn-sm btn-default" name="cancelButton" id="cancelButton"><?php echo _('Cancel'); ?></button>
            <?php } else { ?>
            <a href="manage.php" class="btn btn-sm btn-default"><?php echo _("Cancel"); ?></a>
            <?php } ?>
        </div>

    </form>

    <?php
    do_page_end(true);
    exit();
}

function get_sr_ajax_data()
{
    $arr = array();
    $reports = get_user_meta('0', 'scheduled_reports');
    ($reports) ? $reports = unserialize($reports) : $reports = array();
    $num = count($reports);

    $mi = array();
    foreach ($reports as $id => $r) {
        if (empty($r['dontdisplay'])) {
            $mi[] = array(
                "type" => "link",
                "title" => encode_form_val($r["name"]),
                "order" => 100,
                "opts" => array(
                    "href" => "../includes/components/scheduledreporting/schedulereport.php?visit=1&id=" . $id . "&nsp=" . get_nagios_session_protector_id(),
                    "id" => "scheduledreport-" . $id,
                )
            );
        }
    }

    $html = get_menu_items_html($mi);
    $arr['html'] = $html;
    $arr['count'] = $num;
    print json_encode($arr);
}
