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

# ----- 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
    if (Resource::ItemExists($ResourceId))
    {
        # if field ID is valid for resource
        $Resource = new Resource($ResourceId);
        if ($Resource->Schema()->FieldExists($FieldId))
        {
            # if URL field was specified and user has permission to view it
            $Field = $Resource->Schema()->GetField($FieldId);
            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"] :
            OurBaseUrl()."index.php");
}
