<?PHP
#
#   FILE:  TaskQueue.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

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

global $H_PageUrl;

PageTitle("Task Queue");

# the base URL for this page used when refreshing
$H_PageUrl = OurBaseUrl() . "index.php?P=TaskQueue";

# need sysadmin privileges for this page
if (!CheckAuthorization(PRIV_SYSADMIN)) { return; }

# if task execution enable/disable requested
if (isset($_GET["CE"]))
{
    # save new task execution state
    $GLOBALS["AF"]->TaskExecutionEnabled(
            isset($_POST["F_TaskExecutionEnabled"]) ? TRUE : FALSE);
}

# refresh the page every 30 seconds if appropriate. this must come after the
# code that sets whether or not task execution is enabled
if ($GLOBALS["AF"]->TaskExecutionEnabled())
{
    header("Refresh: 30; url=".$H_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")
    {
        $GLOBALS["AF"]->ReQueueOrphanedTask($TaskId);
    }

    # re-queue all orphaned tasks if requested
    elseif ($Action == "REQUEUEALL")
    {
        $OrphanedTasks = $GLOBALS["AF"]->GetOrphanedTaskList();
        foreach ($OrphanedTasks as $Id => $Task)
        {
            $NewPriority = max(1, ($Task["Priority"] - 1));
            $GLOBALS["AF"]->ReQueueOrphanedTask($Id, $NewPriority);
        }
    }

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

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

        # if specified task found
        if ($Task)
        {
            # attempt to load task callback if not already available
            $GLOBALS["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
                $GLOBALS["AF"]->DeleteTask($TaskId);
            }
        }
    }
}
