<?php

function submit_command($command, $command_data = "", $user_id = 0) {

    global $db;

    // use logged in user's id
    if ($user_id == 0 && isset($_SESSION["user_id"]))
        $user_id = $_SESSION["user_id"];

    // make sure user is authorized to submit command
    if (!is_authorized_to_submit_command($command, $command_data)) {

        log_error(LOG_TYPE_AUDIT, "User not authorized to submit command: $command", 0, $user_id);
        return false;
    }

    log_info(LOG_TYPE_AUDIT, "User submitted command: $command", 0, $user_id);

    $bind_array = array(
        ':user_id' => $user_id,
        ':command' => $command,
        ':command_data' => $command_data,
        );

    return $db->exec_query('INSERT INTO commands (user_id, command, command_data) VALUES (:user_id, :command, :command_data)', $bind_array);
}


function is_authorized_to_submit_command($command, $command_data) {

    return defined('SUBSYSTEM') || defined('SUBSYSTEM_CALL') || is_admin() || install_needed();   
}

// wait for a command to be completed
// time_to_wait measured in seconds, 5 second default
// usleep_time is the amount of time to sleep after each check in the loop, 250000 is the default (quarter of a second) AND THE MINIMUM
// usleep_time cannot exceed time_to_wait
// returns false on command not being completed
// or returns the command row if completed
function wait_for_command($command_id, $time_to_wait = 5, $usleep_time = 250000) {

    $time_to_wait = intval($time_to_wait);
    if ($time_to_wait < 1)
        $time_to_wait = 1;

    $usleep_time = intval($usleep_time);
    if ($usleep_time < 250000)
        $usleep_time = 250000;
    if ($usleep_time > ($time_to_wait * 1000000))
        $usleep_time = $time_to_wait * 1000000;

    global $db;

    $bind_array = array(
        ':command_id' => $command_id,
        ':status_code' => COMMAND_STATUS_COMPLETED,
        );

    $now = time();
    while (time() - $now <= $time_to_wait) {

        $command = $db->exec_query('SELECT * FROM commands WHERE command_id = :command_id AND status_code = :status_code LIMIT 1', $bind_array);
        if (is_array($command) && count($command) == 1)
            return $command[0];

        usleep($usleep_time);
    }

    return false;
}