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

PageTitle("Populate Metadata Field");

# ----- CONFIGURATION  -------------------------------------------------------

# location of vocabulary (.voc) files
$PathToVocabularyFiles = "data/Vocabularies/";


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


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

/**
* Add new terms.
* @param object $Factory Factory object for term class.
* @param int ID of metadata field with which the terms are associated.
* @param array $TermNames Term names.
* @param object $Qualifier Qualifier to associate with new terms.
* @return int Number of items added.
*/
function AddTerms($Factory, $FieldId, $TermNames, $Qualifier = NULL)
{
    # for each supplied term name
    $ItemClassName = $Factory->GetItemClassName();
    $TermCount = 0;
    foreach ($TermNames as $Name)
    {
        # if term does not exist with this name
        $Name = trim($Name);
        if ($Factory->GetItemByName($Name) === NULL)
        {
            # add term
            $NewTerm = new $ItemClassName(NULL, $Name, $FieldId);
            $TermCount++;

            # assign qualifier to term if supplied
            if ($Qualifier !== NULL)
            {
                $NewTerm->Qualifier($Qualifier);
            }
        }
    }

    # return count of terms added to caller
    return $TermCount;
}


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

# check that user has permission for this
if (!CheckAuthorization(PRIV_COLLECTIONADMIN)) {  return;  }

# check to make sure we have at least PHP 5.x (for SimpleXML support)
if (PHP_VERSION < 5)
{
    $G_ErrorMessages[] = "PHP version 5.x or later is required for the <i>Populate Field</i> feature.  You currently have PHP version ".PHP_VERSION.".";
}
else
{
    # load metadata field
    if (isset($_GET["ID"]))
    {
        $Schema = new MetadataSchema();
        $G_Field = $Schema->GetField(intval($_GET["ID"]));
    }
    if (!isset($G_Field) || ($G_Field->Status() != MetadataSchema::MDFSTAT_OK))
    {
        $G_ErrorMessages[] = "Could not load metadata field.";
    }
    elseif (!($G_Field->Type() & (MetadataSchema::MDFTYPE_CONTROLLEDNAME|MetadataSchema::MDFTYPE_OPTION|MetadataSchema::MDFTYPE_TREE)))
    {
        $G_ErrorMessages[] = "The <i>".$G_Field->GetDisplayName()."</i> field is not one of the"
                ." types for which population is support.  Only <b>Controlled Name</b>,"
                ." <b>Option</b>, and <b>Tree</b> fields can be populated with"
                ." the prepackaged vocabularies.";
    }

    # if vocabulary specified
    if (isset($_GET["VH"]))
    {
        # load specified vocabulary
        $VocFact = new VocabularyFactory($PathToVocabularyFiles);
        $G_Vocabulary = $VocFact->GetVocabularyByHash($_GET["VH"]);
        if ($G_Vocabulary === NULL)
        {
            $G_ErrorMessages[] = "No vocabulary file found with specified hash.";
        }
        else
        {
            # if vocabulary import was confirmed
            if (isset($_GET["CP"]) && !isset($G_ErrorMessages))
            {
                # import specified vocabulary
                $G_IsVocabImport = TRUE;
                $Terms = $G_Vocabulary->TermList();
                $FactoryClass = ($G_Field->Type() == MetadataSchema::MDFTYPE_TREE)
                        ? "ClassificationFactory" : "ControlledNameFactory";
                $Factory = new $FactoryClass($G_Field->Id());

                # if new vocabulary has a qualifier
                if ($G_Vocabulary->HasQualifier())
                {
                    # if we already have a qualifier with the same name
                    $QualFact = new QualifierFactory();
                    if ($QualFact->NameIsInUse($G_Vocabulary->QualifierName()))
                    {
                        # if details for existing and new qualifier do not match
                        $Qualifier = $QualFact->GetItemByName(
                                $G_Vocabulary->QualifierName());
                        if ($G_Vocabulary->QualifierNamespace() != $Qualifier->NSpace()
                                || ($G_Vocabulary->QualifierUrl() != $Qualifier->Url()))
                        {
                            # error out
                            $G_ErrorMessages[] = "The vocabulary <i>".$G_Vocabulary->Name()
                                    ."</i> specifies a qualifier <i>"
                                    .$G_Vocabulary->QualifierName()."</i> that conflicts"
                                    ." with an existing qualifier (has the same name but"
                                    ." a different namespace or URL or both).";
                        }
                        else
                        {
                            # add new vocabulary with qualifier
                            $G_AddedItemCount = AddTerms(
                                    $Factory, $G_Field->Id(), $Terms, $Qualifier);
                            $G_Field->AssociateWithQualifier($Qualifier);
                        }
                    }
                    else
                    {
                        # add new vocabulary with qualifier
                        $Qualifier = new Qualifier();
                        $Qualifier->Name($G_Vocabulary->QualifierName());
                        $Qualifier->NSpace($G_Vocabulary->QualifierNamespace());
                        $Qualifier->Url($G_Vocabulary->QualifierUrl());
                        $G_AddedItemCount = AddTerms(
                                $Factory, $G_Field->Id(), $Terms, $Qualifier);
                        $G_Field->AssociateWithQualifier($Qualifier);
                    }
                }
                else
                {
                    # add new vocabulary
                    $G_AddedItemCount = AddTerms($Factory, $G_Field->Id(), $Terms);
                }
            }
            else
            {
                # set flag to indicate preview/confirm
                $G_IsVocabPreview = TRUE;
            }
        }
    }
    else
    {
        # load available vocabularies
        $VocFact = new VocabularyFactory($PathToVocabularyFiles);
        $G_Vocabularies = $VocFact->GetVocabularies();
        if (count($G_Vocabularies) == 0)
        {
            $G_ErrorMessages[] = "No vocabulary files found in <i>"
                    .$PathToVocabularyFiles."</i>.";
        }
    }
}
