<?PHP
#
#   FILE:  GoTo.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

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

# if resource ID and field ID were specified
if (isset($_GET["ID"]) && isset($_GET["MF"]))
{
    # grab resource record ID and metadata field ID
    $ResourceId = $_GET["ID"];
    $FieldId = $_GET["MF"];

    # if resource ID is valid
    $Resource = new Resource($_GET["ID"]);
    if ($Resource->Status() != -1)
    {
        # if field ID is valid
        $Schema = new MetadataSchema();
        $Field = $Schema->GetField($_GET["MF"]);
        if ($Field->Status() != MetadataSchema::MDFSTAT_FIELDDOESNOTEXIST)
        {
            # if URL field was specified and user has permission to view it
            if (($Field->Type() == MetadataSchema::MDFTYPE_URL)
                    && ($Resource->UserCanViewField($G_User, $Field)))
            {
                # load URL to go to
                $Url = $Resource->Get($Field);

                # allow plugins to modify the value
                $SignalResult = $AF->SignalEvent(
                    "EVENT_FIELD_DISPLAY_FILTER", array(
                        "Field" => $Field,
                        "Resource" => $Resource,
                        "Value" => $Url));
                $Url = $SignalResult["Value"];

                # don't use URLs that are definitely invalid
                if (!preg_match('/^\s*[a-zA-Z]+:\/\//', $Url))
                {
                    unset($Url);
                }
            }
        }
    }
}

# if we found URL to go to
if (isset($Url))
{
    # signal URL click event
    $AF->SignalEvent("EVENT_URL_FIELD_CLICK", array(
            "ResourceId" => $Resource->Id(),
            "FieldId" => $Field->Id()));

    # go to page specified by URL
    $AF->SetJumpToPage($Url);
}
else
{
    # return to calling page
    $AF->SetJumpToPage(
            isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "index.php");
}
