<?PHP
#
#   FILE:  TaskQueue.php
#
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

# ----- LOCAL FUNCTIONS ------------------------------------------------------

/**
 * Get the URL of the current page.
 * @return the URL of the current page
 */
function GetPageUrl()
{
    $Url = OurBaseUrl() . "index.php";

    if (isset($_GET["P"]))
    {
        $Url .= "?P=" . $_GET["P"];
    }

    return $Url;
}

# ----- MAIN -----------------------------------------------------------------

PageTitle("Task Queue");

# need sysadmin privileges for this page
CheckAuthorization(PRIV_SYSADMIN);

# refresh the page every 30 seconds
$PageUrl = GetPageUrl();
header("Refresh: 30; url=".$PageUrl);

# if action requested
if (isset($_GET["AC"]) && isset($_GET["ID"]))
{
    $Action = $_GET["AC"];
    $TaskId = intval($_GET["ID"]);

    # re-queue orphaned task if requested
    if ($Action == "REQUEUE")
    {
        $AF->ReQueueOrphanedTask($TaskId);
    }

    # remove orphaned task if requested
    else if ($Action == "DELETE")
    {
        $AF->DeleteTask($TaskId);
    }

    # run task in foreground if requested
    else if ($Action == "RUN")
    {
        # retrieve task
        $Task = $AF->GetTask($TaskId);

        # if specified task found
        if ($Task)
        {
            # attempt to load task callback if not already available
            $AF->LoadFunction($Task["Callback"]);

            # if callback appears callable
            if (is_callable($Task["Callback"]))
            {
                # run task
                if ($Task["Parameters"])
                {
                    call_user_func_array($Task["Callback"], $Task["Parameters"]);
                }
                else
                {
                    call_user_func($Task["Callback"]);
                }

                # remove task from queue
                $AF->DeleteTask($TaskId);
            }
        }
    }
}
