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

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

function LoadVariables()
{
    global $Schema, $F_FieldId, $F_FieldName, $F_Description, $F_FieldType,
        $F_Enabled, $F_Optional, $F_Viewable, $F_DefaultValue,
        $F_IncludeInKeywordSearch, $F_IncludeInAdvancedSearch,
        $F_IncludeInSortOptions, $F_SearchWeight, $F_TextFieldSize,
        $F_MaxLength, $F_MinValue, $F_MaxValue, $F_DateFormat,
        $F_ParagraphRows, $F_ParagraphCols, $F_FlagOnLabel, $F_FlagOffLabel,
        $F_AllowMultiple, $ResetFieldType, $F_DefaultAltText, $F_MaxHeight,
        $F_MaxWidth, $F_MaxPreviewHeight, $F_MaxPreviewWidth,
        $F_MaxThumbnailHeight, $F_MaxThumbnailWidth, $F_UsesQualifiers,
        $F_HasItemLevelQualifiers, $F_DefaultQualifier, $F_UseForOaiSets,
        $F_PointPrecision, $F_PointDecimalDigits, $F_DefaultValue2,
        $F_UpdateMethod, $F_AllowHTML, $F_ShowQualifiers;

    # reset field type when coming from DBEditor
    if ($ResetFieldType)
    {
        $F_FieldType = -1;
    }

    if (isset($_GET["F_FieldType"]))
        $F_FieldType = $_GET["F_FieldType"];

    if (is_numeric($F_FieldId))
    {
        # Get the field
        $Field = $Schema->GetField($F_FieldId);

        # load fieldtype if user came from DBEditor page
        if (is_null($F_FieldType) || $F_FieldType == -1)
        {
            $F_FieldType = $Field->Type();
        }

        # Load the form data from the field object
        $F_FieldName = $Field->Name();
        foreach( array("Description","Enabled","Optional",
                       "Viewable","UsesQualifiers","HasItemLevelQualifiers",
                       "DefaultQualifier","IncludeInKeywordSearch",
                       "IncludeInAdvancedSearch","IncludeInSortOptions",
                       "SearchWeight","TextFieldSize",
                       "MaxLength","MinValue","MaxValue","DateFormat",
                       "ParagraphRows","ParagraphCols","FlagOnLabel",
                       "FlagOffLabel","AllowMultiple","DefaultAltText",
                       "MaxHeight","MaxWidth","MaxPreviewHeight",
                       "MaxPreviewWidth","MaxThumbnailHeight",
                       "MaxThumbnailWidth", "UseForOaiSets","PointPrecision",
                       "PointDecimalDigits", "UpdateMethod", "AllowHTML",
                       "ShowQualifiers"
                     ) as $Var )
        {
            eval('$F_'.$Var.' = $Field->'.$Var.'();');
        }

        if ($Field->Type() == MetadataSchema::MDFTYPE_POINT)
        {
            $tmp = $Field->DefaultValue();
            $F_DefaultValue  = $tmp["X"];
            $F_DefaultValue2 = $tmp["Y"];
        }
        else
        {
            $F_DefaultValue = $Field->DefaultValue();
        }
    }

    # first time in, all vars are NULL
    if (empty($F_FieldType))
        $F_FieldType = MetadataSchema::MDFTYPE_TEXT;
}

# return true if updating field
function UpdatingField()
{
    global $F_FieldId, $Schema;

    # CHANGE THIS to use IsTempField()
    if ($F_FieldId > 0)
    {
        return TRUE;
    }
    else
        return FALSE;
}

function PrintHeading()
{
    global $F_FieldId;

    # CHANGE THIS to use IsTempField()
    if ($F_FieldId > 0)
    {
        print "Update Metadata Field";
    }
    else
        print "Add Metadata Field";
}

function PrintSubmitButton()
{
    global $F_FieldId;

    # CHANGE THIS to use IsTempField()
    if ($F_FieldId > 0)
        print "Update Field";
    else
        print "Add New Field";
}

function PrintRawFieldName()
{
    global $F_FieldName;

    if (isset($F_FieldName))
        print $F_FieldName;
}

function PrintFieldName()
{
    global $F_FieldId, $F_FieldType, $F_FieldName, $Schema;

    if (isset($F_FieldId))
    {
        # Get the field
        $Field = $Schema->GetField($F_FieldId);
        if (isset($F_FieldName))
        {
            PrintTextFieldName();
        }
    }
    else
        PrintTextFieldName();
}

function GetAllowedFieldTypes()
{
    global $F_FieldId, $Schema;

    $Field = $Schema->GetField($F_FieldId);

    if (!$Field->IsTempItem())
    {
        # retrieve allowed conversions types from field
        $Field = $Schema->GetField($F_FieldId);
        $ConversionTypes = $Field->GetAllowedConversionTypes();

        return $ConversionTypes;
    }

    else
    {
        $AllTypes = $Schema->GetAllowedFieldTypes();

        return $AllTypes;
    }
}

function PrintEnabledYesNo()
{
    global $F_Enabled;

    print ($F_Enabled ? "Yes" : "No");
}

function PrintEnabled()
{
    global $F_FieldId, $F_FieldType, $F_FieldEnabled, $Schema;

    if (isset($F_FieldId))
    {
        # Get the field
        $Field = $Schema->GetField($F_FieldId);
        if (MetadataSchema::FieldToStdNameMapping($Field->Id()))
        {
            PrintStaticEnabled();
        }
        else
        {
            PrintFlagEnabled();
        }
    }
    else
    {
        PrintFlagEnabled();
    }
}

function PrintOptionalYesNo()
{
    global $F_Optional;

    print ($F_Optional ? "Yes" : "No");
}

function PrintOptional()
{
    PrintFlagOptional();
}

function PrintViewable()
{
    global $F_FieldId, $F_FieldType, $F_FieldViewable, $Schema;

    if (isset($F_FieldId))
    {
        # Get the field
        $Field = $Schema->GetField($F_FieldId);
        PrintFlagViewable();
    }
    else
        PrintFlagViewable();
}

function PrintFieldTypeAsName()
{
    global $F_FieldTypeAsName;

    print $F_FieldTypeAsName;
}

function PrintFieldType()
{
    global $F_FieldId, $F_FieldType, $F_FieldTypeAsName, $Schema;

    $Items = GetAllowedFieldTypes();

    if (isset($F_FieldId))
    {

        $Field = $Schema->GetField($F_FieldId);

        if ((MetadataSchema::FieldToStdNameMapping($Field->Id())) || count($Items) == 0)
        {
            $F_FieldTypeAsName = $Field->TypeAsName();
            PrintStaticFieldType();
        }
        else
        {
            PrintFieldTypeBegin();
            PrintOptionList("Submit", $Items, $F_FieldType, 1, 1, NULL, false);
            PrintFieldTypeEnd();
        }
    }
    else
    {
        PrintFieldTypeBegin();
        PrintOptionList("Submit", $Items, $F_FieldType, 1, 1, NULL, false);
        PrintFieldTypeEnd();
    }
}

function PrintUpdateMethod()
{
    global $F_UpdateMethod, $F_FieldId, $Schema;

    $Field = $Schema->GetFIeld($F_FieldId);

    if (   $Field->Name() == "Date Of Record Release" )
    {
        print "Updated automatically when the record is released";
    }
    else if ($Field->Name() == "Date Of Record Creation" ||
             $Field->Name() == "Date Last Modified"      )
    {

        print (MetadataField::$UpdateTypes[$Field->UpdateMethod()]);
    }
    else
    {
        PrintOptionList("F_UpdateMethod",
                        MetadataField::$UpdateTypes,
                        $F_UpdateMethod, 0, 1, NULL, false);
    }
}

function PrintDescription()
{
    global $F_Description;

    if (isset($F_Description))
        print $F_Description;
}

function PrintFieldId()
{
    global $F_FieldId;

    if (isset($F_FieldId))
        print $F_FieldId;
}

function SelectIfOptionalYes()
{
    global $F_Optional;

    if (!isset($F_Optional) || $F_Optional == 1)
        print "selected";
}

function SelectIfOptionalNo()
{
    global $F_Optional;

    if (isset($F_Optional) && $F_Optional == 0)
        print "selected";
}

function SelectIfUsesQualifiersYes()
{
    global $F_UsesQualifiers;

    if (!isset($F_UsesQualifiers) || $F_UsesQualifiers == 1)
        print "selected";
}

function SelectIfUsesQualifiersNo()
{
    global $F_UsesQualifiers;

    if (isset($F_UsesQualifiers) && $F_UsesQualifiers == 0)
        print "selected";
}

function SelectIfHasItemLevelQualifiersYes()
{
    global $F_HasItemLevelQualifiers;

    if (!isset($F_HasItemLevelQualifiers) || $F_HasItemLevelQualifiers == 1)
        print "selected";
}

function SelectIfHasItemLevelQualifiersNo()
{
    global $F_HasItemLevelQualifiers;

    if (isset($F_HasItemLevelQualifiers) && $F_HasItemLevelQualifiers == 0)
        print "selected";
}

function PrintDefaultQualifier()
{
    global $F_DefaultQualifier;
    global $F_FieldId;
    global $Schema;

    if (isset($F_FieldId))
    {
        $Field = $Schema->GetField($F_FieldId);
        $Items = $Field->AssociatedQualifierList();
    }
    $Items["--"] = "--";
    ksort($Items);

    PrintOptionList("F_DefaultQualifier", $Items, $F_DefaultQualifier,
        0, 1, NULL, false);
}

function PrintAllowedQualifiers()
{
    global $F_FieldId;
    global $Schema;

    if (isset($F_FieldId))
    {
        $Field = $Schema->GetField($F_FieldId);
        $Items = $Field->AssociatedQualifierList();
    }

    if (count($Items) == 0)
        $Items["--"] = "--";

    PrintOptionList("F_AllowedQualifiers", $Items, NULL, 0, 4, NULL, false);
}

function PrintAvailableQualifiers()
{
    global $F_FieldId;
    global $Schema;

    if (isset($F_FieldId))
    {
        $Field = $Schema->GetField($F_FieldId);
        $Items = $Field->UnassociatedQualifierList();
    }
    else
    {
        $QFactory = new QualifierFactory();
        $Items = $QFactory->QualifierList();
    }

    if (count($Items) == 0)
        $Items["--"] = "--";

    PrintOptionList("F_AvailableQualifiers", $Items, NULL, 0, 4, NULL, false);
}

function SelectIfKeywordSearchYes()
{
    global $F_IncludeInKeywordSearch;

    if (!isset($F_IncludeInKeywordSearch) || $F_IncludeInKeywordSearch == 1)
        print "selected";
}

function SelectIfKeywordSearchNo()
{
    global $F_IncludeInKeywordSearch;

    if (isset($F_IncludeInKeywordSearch) && $F_IncludeInKeywordSearch == 0)
        print "selected";
}

function SelectIfAdvancedSearchYes()
{
    global $F_IncludeInAdvancedSearch;

    if (!isset($F_IncludeInAdvancedSearch) || $F_IncludeInAdvancedSearch == 1)
        print "selected";
}

function SelectIfAdvancedSearchNo()
{
    global $F_IncludeInAdvancedSearch;

    if (isset($F_IncludeInAdvancedSearch) && $F_IncludeInAdvancedSearch == 0)
        print "selected";
}

function SelectIfSortOptionYes()
{
    global $F_IncludeInSortOptions;

    if (!isset($F_IncludeInSortOptions) || $F_IncludeInSortOptions == 1)
        print "selected";
}

function SelectIfSortOptionNo()
{
    global $F_IncludeInSortOptions;

    if (isset($F_IncludeInSortOptions) && $F_IncludeInSortOptions == 0)
        print "selected";
}

function SelectIfUseForOaiSetsNo()
{
    global $F_UseForOaiSets;

    if (!isset($F_UseForOaiSets) || $F_UseForOaiSets == 0)
        print "selected";
}

function SelectIfUseForOaiSetsYes()
{
    global $F_UseForOaiSets;

    if (isset($F_UseForOaiSets) && $F_UseForOaiSets == 1)
        print "selected";
}


function SelectIfAllowMultipleYes()
{
    global $F_AllowMultiple;

    if (!isset($F_AllowMultiple) || $F_AllowMultiple == 1)
        print "selected";
}

function SelectIfAllowMultipleNo()
{
    global $F_AllowMultiple;

    if (isset($F_AllowMultiple) && $F_AllowMultiple == 0)
        print "selected";
}

function SelectIfDefaultValueYes()
{
    global $F_DefaultValue;

    if (!isset($F_DefaultValue) || $F_DefaultValue == 1)
        print "selected";
}

function SelectIfDefaultValueNo()
{
    global $F_DefaultValue;

    if (isset($F_DefaultValue) && $F_DefaultValue == 0)
        print "selected";
}

function SelectIfEnabledYes()
{
    global $F_Enabled;

    if (!isset($F_Enabled) || $F_Enabled == 1)
        print "selected";
}

function SelectIfEnabledNo()
{
    global $F_Enabled;

    if (isset($F_Enabled) && $F_Enabled == 0)
        print "selected";
}

function SelectIfViewableYes()
{
    global $F_Viewable;

    if (!isset($F_Viewable) || $F_Viewable == 1)
        print "selected";
}

function SelectIfViewableNo()
{
    global $F_Viewable;

    if (isset($F_Viewable) && $F_Viewable == 0)
        print "selected";
}

function PrintDefaultValue()
{
    global $F_DefaultValue;
    if (isset($F_DefaultValue))
        print $F_DefaultValue;
}

function PrintDefaultValue2()
{
    global $F_DefaultValue2;
    if (isset($F_DefaultValue2))
        print $F_DefaultValue2;

}

function PrintErrorMessage()
{
    global $ErrorMessage;

    if (isset($ErrorMessage))
    print $ErrorMessage;
}

function PrintTextFieldSize()
{
    global $F_TextFieldSize, $F_FieldType;

    if (isset($F_TextFieldSize))
        print $F_TextFieldSize;
    else
    {
        switch($F_FieldType)
        {
            case MetadataSchema::MDFTYPE_TEXT:
            case MetadataSchema::MDFTYPE_URL:
                print 50;
                break;

            case MetadataSchema::MDFTYPE_NUMBER:
                print 4;
                break;

            case MetadataSchema::MDFTYPE_POINT:
            case MetadataSchema::MDFTYPE_DATE:
                print 10;
                break;

            default:
                break;
        }
    }
}

function PrintMaxLength()
{
    global $F_MaxLength;

    if (isset($F_MaxLength) && (($F_MaxLength != 100) || !FieldTypeIsUrl()))
        print $F_MaxLength;
    else
        print FieldTypeIsUrl() ? 255 : 100;
}

function PrintMinValue()
{
    global $F_MinValue;

    if (isset($F_MinValue))
        print $F_MinValue;
    else
        print 1;
}

function PrintMaxValue()
{
    global $F_MaxValue;

    # (9999 was chose as default max value because default number field length is 4)
    $Value = isset($F_MaxValue) ? $F_MaxValue : 9999;
    print($Value);
}

function PrintSearchWeight()
{
    global $F_SearchWeight;

    if (isset($F_SearchWeight))
        print $F_SearchWeight;
    else
        print 1;
}

function PrintDefaultAltText()
{
    global $F_DefaultAltText;

    if (isset($F_DefaultAltText))
        print $F_DefaultAltText;
}

function PrintMaxHeight()
{
    global $F_MaxHeight;

    if (isset($F_MaxHeight))
        print $F_MaxHeight;
    else
        print 500;
}

function PrintMaxWidth()
{
    global $F_MaxWidth;

    if (isset($F_MaxWidth))
        print $F_MaxWidth;
    else
        print 500;
}

function PrintMaxPreviewHeight()
{
    global $F_MaxPreviewHeight;

    if (isset($F_MaxPreviewHeight))
        print $F_MaxPreviewHeight;
    else
        print 100;
}

function PrintMaxPreviewWidth()
{
    global $F_MaxPreviewWidth;

    if (isset($F_MaxPreviewWidth))
        print $F_MaxPreviewWidth;
    else
        print 100;
}

function PrintMaxThumbnailHeight()
{
    global $F_MaxThumbnailHeight;

    if (isset($F_MaxThumbnailHeight))
        print $F_MaxThumbnailHeight;
    else
        print 50;
}

function PrintMaxThumbnailWidth()
{
    global $F_MaxThumbnailWidth;

    if (isset($F_MaxThumbnailWidth))
        print $F_MaxThumbnailWidth;
    else
        print 50;
}

function PrintParagraphRows()
{
    global $F_ParagraphRows;

    if (isset($F_ParagraphRows))
        print $F_ParagraphRows;
    else
        print 4;
}

function PrintParagraphCols()
{
    global $F_ParagraphCols;

    if (isset($F_ParagraphCols))
        print $F_ParagraphCols;
    else
        print 50;
}

function PrintFlagOnLabel()
{
    global $F_FlagOnLabel;

    if (isset($F_FlagOnLabel))
        print $F_FlagOnLabel;
    else
        print "On";
}

function PrintFlagOffLabel()
{
    global $F_FlagOffLabel;

    if (isset($F_FlagOffLabel))
        print $F_FlagOffLabel;
    else
        print "Off";
}

function PrintPointPrecision()
{
    global $F_PointPrecision;
    if (isset($F_PointPrecision))
        print $F_PointPrecision;
    else
        print 8;
}

function PrintPointDigits()
{
    global $F_PointDecimalDigits;
    if (isset($F_PointDecimalDigits))
        print $F_PointDecimalDigits;
    else
        print 5;
}

function FieldIsTemp()
{
    global $G_Field;

    return $G_Field->IsTempItem();
}

function FieldTypeIsText()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_TEXT);
}

function FieldTypeIsNumber()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_NUMBER);
}

function FieldTypeIsDate()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_DATE);
}

function FieldTypeIsTree()
{
    global $F_FieldType, $F_FieldId;

    return ($F_FieldType == MetadataSchema::MDFTYPE_TREE);
}

function FieldTypeIsUser()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_USER);
}

function FieldTypeIsTimestamp()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_TIMESTAMP);
}

function FieldTypeIsParagraph()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_PARAGRAPH);
}

function FieldTypeIsFlag()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_FLAG);
}

function FieldTypeIsOption()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_OPTION);
}

function FieldTypeIsControlledName()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_CONTROLLEDNAME);
}

function FieldTypeIsImage()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_IMAGE);
}

function FieldTypeIsFile()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_FILE);
}

function FieldTypeIsUrl()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_URL);
}

function FieldTypeIsPoint()
{
    global $F_FieldType;

    return ($F_FieldType == MetadataSchema::MDFTYPE_POINT);
}

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

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

require_once "lib/AxisPHP/Axis--StandardLibrary.php";

# non-standard global variables
global $ErrorMessage, $F_AllowMultiple, $F_DateFormat, $F_DefaultAltText,
    $F_DefaultQualifier, $F_DefaultValue, $F_DefaultValue2, $F_Description,
    $F_Enabled, $F_FieldEnabled, $F_FieldId, $F_FieldName, $F_FieldOptional,
    $F_FieldType, $F_FieldTypeAsName, $F_FieldViewable, $F_FlagOffLabel,
    $F_FlagOnLabel, $F_HasItemLevelQualifiers, $F_IncludeInAdvancedSearch,
    $F_IncludeInKeywordSearch, $F_IncludeInSortOptions, $F_MaxHeight,
    $F_MaxLength, $F_MaxPreviewHeight, $F_MaxPreviewWidth,
    $F_MaxThumbnailHeight, $F_MaxThumbnailWidth, $F_MaxValue, $F_MaxWidth,
    $F_MinValue, $F_Optional, $F_ParagraphCols, $F_ParagraphRows,
    $F_SearchWeight, $F_TextFieldSize, $F_UseForOaiSets, $F_UsesQualifiers,
    $F_Viewable, $F_PointPrecision, $F_PointDecimalDigits, $ResetFieldType,
    $Schema, $F_UpdateMethod, $F_AllowHTML, $F_ShowQualifiers;
global $G_PrivilegeList;
global $G_Field;

# if F_FieldType is -1, then came here from DBEditor screen
if (isset($_GET["F_FieldType"]) && $_GET["F_FieldType"] == -1)
    $ResetFieldType=TRUE;

PageTitle(isset($F_FieldId) ? "Edit Metadata Field" : "Add Metadata Field");

if (!CheckAuthorization(PRIV_SYSADMIN, PRIV_COLLECTIONADMIN)) {  return;  }

$Schema = new MetadataSchema();

# see if editing an existing field
if (isset($_GET["F_FieldId"]))
{
    $F_FieldId = $_GET["F_FieldId"];
    $Schema->SetCurrentEditedItemId($F_FieldId);
}
# or get currently edited Field
else
{
    $F_FieldId = $Schema->GetCurrentEditedItemId();
}

if (isset($_POST["Submit"]))
    $Submit = $_POST["Submit"];
else
    $Submit = NULL;

# Add New Field selected, so create a new field
if (substr($Submit, 0, 3) == "Add")
{
    # remove any old temp field
    if (isset($F_FieldId))
    {
        $Field = $Schema->GetField($F_FieldId);

        if ($Field->IsTempItem())
        {
            $Schema->DropField($F_FieldId);
        }
    }

    # clear current edited field id
    $Schema->ClearCurrentEditedItemId();

    # create a new temp field, default to text type
    $Field = $Schema->AddField(NULL, MetadataSchema::MDFTYPE_TEXT);
    $F_FieldId = $Field->Id();
    $Schema->SetCurrentEditedItemId($F_FieldId);
}

# return to Edit metadata fields page
else if (substr($Submit, 0, 4) == "Edit")
{
    $AF->SetJumpToPage("DBEditor");
    return;
}

LoadVariables();

# load values for privilege editing
$G_Field = $Schema->GetField($F_FieldId);
$PrivFactory = new PrivilegeFactory();
$G_PrivilegeList = array(0 => "--") + $PrivFactory->GetPrivileges(TRUE, FALSE);

$ErrorMessage = isset($_GET["ErrorMessage"]) ?
    StripXSSThreats($_GET["ErrorMessage"]):NULL;
