<?php
require_once(dirname(__FILE__) . '/../includes/base.inc.php');
block_non_admins();

route_request();
function route_request() {

    $pageopt = get_pageopt();

    switch ($pageopt) {

        case 'delete':
            delete_dashlet();
            break;

        case 'upload':
            upload_dashlet();
            break;

        case 'download':
            download_dashlet();
            break;

        //case 'checkupdates':

        //case 'installupdates':

        default:
            show_dashlets();
            break;
    }
}

function show_dashlets() {

    global $dashlets;

    $title = _('Manage Dashlets');
    child_page($title);
    echo well_top_page_header($title);
    
    echo '<p>' . _("Manage the dashlets that are installed on this system. Need a custom dashlet created to extend Nagios Fusion's capabilities?") . 
        ' <a href="http://www.nagios.com/contact/" target="_blank">' . _('Contact us') . '</a> ' . _('for pricing information.') . '<br />' .
        _('You can find more dashlets') . ' <a href="http://exchange.nagios.org/directory/Addons/Dashlets/" target="_blank">' . _('on the Exchange') . '</a>.</p>';

    $update_dashlets = array();

    ?>

    <div class="well" style="margin-top: 10px;">
        <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin: 0;">

            <input type="hidden" name="upload" value="1">
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000">

            <div class="fl upload-dashlet" style="height: 29px; line-height: 29px; margin-right: 10px; font-weight: bold;"><?php echo _('Upload a Dashlet'); ?></div>
            <div class="fl" style="margin-right: 10px;">
                <div class="input-group" style="width: 240px;">
                    <span class="input-group-btn">
                        <span class="btn btn-sm btn-default btn-file">
                            <?php echo _('Browse'); ?>&hellip; <input type="file" name="uploadedfile">
                        </span>
                    </span>
                    <input type="text" class="form-control" style="width: 200px;" readonly>
                </div>
            </div>
            <div class="fl">
                <button type="submit" class="btn btn-sm btn-primary"><?php echo _('Upload &amp; Install'); ?></button>
            </div>

            <div class="fr">
                <a href="https://exchange.nagios.org/directory/Addons/Dashlets" class="btn btn-sm btn-default"><?php echo _('More Dashlets'); ?> <i class="fa fa-external-link r"></i></a>
            </div>

            <div class="clear"></div>
        </form>
    </div>

    <?php

    foreach ($dashlets as $dashlet) {

        // Ignore the test dashlet we use as an example
        if (isset($dashlet[DASHLET_NAME]) && $dashlet[DASHLET_NAME] != 'Test')
            echo get_dashlet_preview($dashlet, $manage = true);
    }

    exit();
}

function upload_dashlet() {

    check_nagios_session_protector();

    // error in demo
    demo_error('show_dashlets');

    global $dashlets;

    $target_path = get_tmp_dir() . '/';
    $dashlet_file = preg_replace('/[^A-Za-z0-9\.\-]/', '', basename($_FILES['uploadedfile']['name']));
    $target_path .= "dashlet-{$dashlet_file}";

    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

        // fix perms
        chmod($target_path, 0770);
        chgrp($target_path, 'nagios');

        $command_id = submit_command(COMMAND_INSTALL_DASHLET, $dashlet_file);
        if ($command_id === false || $command_id <= 0) {
            flash_message(_('Unable to submit command.'), 'error');
            show_dashlets();
        }

        if ($command = wait_for_command($command_id)) {
            if ($command['result_code'] == COMMAND_RESULT_OK) {
                flash_message(_('Dashlet successfully installed.'));
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit();
            } else {
                if (!empty($command['result'])) {
                    flash_message($command['result'], 'error');
                } else {
                    flash_message(_('Something went wrong installing dashlet.'), 'error');
                }
            }
        } else {
            flash_message(_('Dashlet scheduled for installation.'));
        }
    } else {
        flash_message(_('Unable to move uploaded file. Check your permissions on ') . get_tmp_dir(), 'error');
    }

    show_dashlets();
}

function delete_dashlet() {

    check_nagios_session_protector();

    // error in demo
    demo_error('show_dashlets');

    global $dashlets;

    $name = grab_request_var('delete', '');

    if (empty($name) || empty($dashlets[$name])) {
        flash_message(_('No dashlet with that specified name.'), 'error');
        show_dashlets();
    }

    $command_id = submit_command(COMMAND_DELETE_DASHLET, $name);
    if ($command_id === false || $command_id <= 0) {
        flash_message(_('Unable to submit command.'), 'error');
        show_dashlets();
    }

    if ($command = wait_for_command($command_id)) {

        if ($command['result_code'] == COMMAND_RESULT_OK) {

            flash_message(_('Dashlet successfully deleted.'));
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
            
        } else {
            flash_message(_('Something went wrong deleting dashlet.'), 'error');
        }
    } else {
        flash_message(_('Dashlet scheduled for deletion.'));
    }

    show_dashlets();
}

function download_dashlet() {

    global $dashlets;
    
    // error in demo
    demo_error('show_dashlets');

    $name = grab_request_var('download', '');

    if (empty($name) || empty($dashlets[$name]) || empty($dashlets[$name][DASHLET_DIRECTORY])) {
        flash_message(_('No dashlet with that specified name.'), 'error');
        show_dashlets();
    }

    $dir = $dashlets[$name][DASHLET_DIRECTORY];

    $command_id = submit_command(COMMAND_PACKAGE_DASHLET, $dir);
    if ($command_id === false || $command_id <= 0) {
        flash_message(_('Unable to submit command.'), 'error');
        show_dashlets();
    }

    if ($command = wait_for_command($command_id, $time_to_wait = 10)) {

        if ($command['result_code'] == COMMAND_RESULT_OK) {

            $file = get_tmp_dir() . "/dashlet-{$dir}.zip";

            header('Content-type: ');
            header('Content-length: ' . filesize($file));
            header('Content-Disposition: attachment; filename="' . basename($file) . '"');
            readfile($file);
            exit();

        } else {
            flash_message(_('Something went wrong packaging dashlet.'), 'error');
        }
    } else {
        flash_message(_('Dashlet packaging timed out.'), 'error');
    }

    show_dashlets();
}