#!/usr/bin/env php -q
<?php
//
// Scheduled Reporting Component
//  - Send Report
// Copyright (c) 2011-2017 Nagios Enterprises, LLC. All rights reserved.
//

define("SUBSYSTEM", 1);


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

main();

function main()
{
    global $argv;
    global $cfg;


    $args = parse_argv($argv);
    echo "\nARGV:\n";
    print_r($argv);
    echo "\nARGS:\n";
    print_r($args);
    echo "\n";

    $username = grab_array_var($args, "username", "");
    $reportid = grab_array_var($args, "report", "");


    if ($username == "" || $reportid == "") {
        echo "Improper input.\n";
        echo "Usage: ./sendreport.php --username=[username] --report=[reportid]\n";
        echo "\n";
        exit(1);
    }

    $dbok = db_connect_all();
    if (!$dbok) {
        echo "Unabled to connect to database\n";
        exit(1);
    }

    //get user id
    $userid = get_user_id($username);
    if (empty($userid)) {
        echo "Error: Bad username\n";
        exit(1);
    }

    $sr = scheduledreporting_component_get_report_id($reportid, $userid);

    // Updated so reports created while in the demo stop if the demo expires -SW
    if ($sr['frequency'] != "Once" && enterprise_features_enabled() == false)
        $sr = null;

    if ($sr == null) {
        echo "Error: Bad report\n";
        exit(1);
    }

    //echo "USERID: $userid\n";
    //echo "REPORT ID: $reportid\n";

    $reportname = grab_array_var($sr, "name", "");
    $reporturl = grab_array_var($sr, "url", "");
    $frequency = grab_array_var($sr, "frequency", "");
    $recipients = grab_array_var($sr, "recipients", "");
    $rawsubject = grab_array_var($sr, "subject", "");
    $body = grab_array_var($sr, "body", "");
    $attachments = grab_array_var($sr, "attachments", null);
    $type = grab_array_var($sr, "type", "");

    if ($rawsubject == "") {
        $subject = "Nagios Report";
        if ($reportname != "")
            $subject .= ": " . $reportname;
    } else
        $subject = "Nagios Report: " . $rawsubject;

    echo "SR:\n";
    print_r($sr);
    echo "\n";

    $baseurl = get_external_url();
    $fullname = get_user_attr($userid, "name");

    // Set full body to nothing...
    $fullbody = "";

    // Check if wkhtmltopdf exists and is executable
    if (is_executable("/usr/bin/wkhtmltopdf") == FALSE && $type == "page") {
        $fullbody .= "\n\n************\nERROR: /usr/bin/wkhtmltopdf is not installed - page rendering failed!\n************\n\n";
    }

    $opts = array(
        "to" => $recipients,
        "subject" => $subject,
        "attachment" => array(),
        "message" => $fullbody,
    );

    // add attachments...

    // get options
    $sro = scheduledreporting_component_get_report_options($reporturl);
    echo "SRO:\n";
    print_r($sro);
    echo "\n";

    // get backend ticket
    $backend_ticket = get_user_attr($userid, "backend_ticket");

    // Assemble actual URL that will be gotten 

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

    $fullurl = ($is_nagios_url ? get_external_url() . "/{$reporturl}" : $reporturl);
    //echo "FULLURL: $fullurl\n";

    $urlparts = parse_url($fullurl);

    $newurl = "";
    $newurl .= $urlparts['scheme'];
    $newurl .= "://";
    $newurl .= $urlparts['host'];
    $newurl .= $urlparts['path'];
    $newurl .= "?";
    if (isset($urlparts['query']))
        $newurl .= $urlparts['query'];

    $newurl .= "&username=" . $username;
    $newurl .= "&ticket=" . $backend_ticket;

    // Get user's language
    if ($is_nagios_url) {
        $userlang = get_user_meta($userid, "language");
        $newurl .= "&locale=" . $userlang;
    }

    if (isset($urlparts['fragment']))
        $newurl .= '#' . $urlparts['fragment'];

    //echo "NEWURL: $newurl\n";

    $tmpfiles = array();

    // page rendering
    if ($type == 'page') {
        $makepdf = false;
        if (!is_null($attachments)) {
            if (is_array($attachments)) {
                if (array_key_exists('pdf', $attachments)) {
                    $makepdf = true; 
                }
            }
        } else {
            $makepdf = true;
        }

        if ($makepdf) {
            $aurl = $newurl;
            
            if ($reportname == "")
                $reportname = "page";
            
            $afile = $reportname . ".pdf";
            $fname = get_tmp_dir() . "/scheduledreport-" . $username . "-" . $reportid . "-" . $afile;

            $footer = '--footer-spacing 3 --margin-bottom 15mm --footer-font-size 9 --footer-right "Page [page] of [toPage]" --footer-left "' . get_datetime_string(time(), DT_SHORT_DATE_TIME, DF_AUTO, "null") . '" --header-left "' . $reportname . '"';

            $cmd = "/usr/bin/wkhtmltopdf {$footer} '{$aurl}' " . escapeshellarg($fname) . " 2>&1";
            echo "WKHTMLTOPDF COMMAND: $cmd\n";
            //$fullbody.="WKHTMLTOPDF command: $cmd\n";
            $out = exec($cmd);

            if (!file_exists($fname)) {
                $fullbody .= "\n\n************\nERROR: Failed to render URL '" . $aurl . "' as '" . $fname . "'\n************\n\n";
            } else {
                echo "Rendered URL '" . $aurl . "' as '" . $fname . "'\n";
            }

            // add it to the email
            $opts["attachment"][] = array($fname, $afile);

            // delete file later
            $tmpfiles[] = $fname;
        }
    } else if ($type != 'page') {
        foreach ($attachments as $aid => $aopt) {

            echo "ATTACHMENT[$aid]=$aopt\n";
            $sroa = grab_array_var($sro["attachments"], $aid);

            $aurl = $newurl . "&" . $sroa["urlopts"];
            $afile = $sroa["file"];

            echo "  URL=>$aurl\n";
            echo "  FILE=>$afile\n";

            $fname = get_tmp_dir() . "/scheduledreport-" . $username . "-" . $reportid . "-" . $afile;

            // generate report
            $cmd = "wget --no-check-certificate -O \"$fname\" '$aurl'";
            $out = exec($cmd, $output, $bool);
            scheduled_reporting_component_log("\n\nCMD: $cmd\nRET: $bool\nOUTPUT: " . implode("\n", $output));

            if (!file_exists($fname)) {
                $fullbody .= "\n\n************\nERROR: Failed to fetch attachment '" . $fname . "'\n************\n\n";
            } else {
                echo "Attached: '" . $fname . "'\n";
            }

            // add it to the email
            $opts["attachment"][] = array($fname, $afile);

            // delete file later
            $tmpfiles[] = $fname;
        }
    }

    // Grab the full body text as defined by the user and replace items that need replacing
    $full_body_template = get_user_meta($userid, "scheduled_report_email_template");
    if ($full_body_template == NULL) {
        $full_body_template = "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]";
    }

    // Do some quick checks to replace things
    $replace_reporturl = $baseurl . "?xiwindow=";
    if ($is_nagios_url) {
        $replace_reporturl .= urlencode($reporturl);
    } else {
        $replace_reporturl .= urlencode($fullurl);
    }
    $replace = array($username, $fullname, $replace_reporturl, $baseurl, $body);
    $find = array('[username]', '[name]', '[reporturl]', '[nagiosxiurl]', '[custommessage]');
    $fullbody = str_replace($find, $replace, $full_body_template);

    $opts["message"] = $fullbody;

    echo "EMAIL:\n";
    print_r($opts);
    echo "\n";
    scheduled_reporting_component_log("EMAIL: " . print_r($opts, true) . "\n");

    // Set where email is coming from for PHPmailer log
    $send_mail_referer = "includes/components/scheduledreporting > Scheduled Report";

    send_email($opts, $debugmsg, $send_mail_referer);

    echo "\nDEBUG:\n";
    echo $debugmsg;
    echo "\n\n";
    scheduled_reporting_component_log("DEBUG: {$debugmsg} \n");

    // delete temp files
    foreach ($tmpfiles as $tf) {
        echo "DELETING $tf\n";
        exec("rm -f $tf");
    }

    // delete one-time reports
    echo "FREQ: $frequency<BR>";
    if ($frequency == "Once")
        scheduledreporting_component_delete_report($reportid, $userid);
}