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

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

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

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

/**
* Retrieve list of available folders of resources to export.
* @return array Array with Folder names for the values and Folder IDs for
*       the index, plus an entry for all resources with -1 as the index.
*/
function GetAvailableSources()
{
    # start with empty list of sources
    $Sources = array();

    # if Folders plugin is available
    if ($GLOBALS["G_PluginManager"]->PluginEnabled("Folders"))
    {
        # retrieve folders
        $Folders = array();
        $FFactory = new Folders_FolderFactory($GLOBALS["G_User"]->Id());
        $ResourceFolder = $FFactory->GetResourceFolder();
        $FolderIds = $ResourceFolder->GetItemIds();
        foreach ($FolderIds as $Id)
        {
            $Folders[$Id] = new Folder($Id);
        }

        # assemble source list from folder names
        foreach ($Folders as $Id => $Folder)
        {
            $FolderItemCount = $Folder->GetItemCount();
            $Sources[$Id] = $Folder->Name()." (".$FolderItemCount." item"
                    .(($FolderItemCount == 1) ? "" : "s").")";
        }
    }

    # add option list selection for all resources
    foreach (MetadataSchema::GetAllSchemas() as $Id => $Schema)
    {
        $Sources[-1 - $Id] = "ALL ".strtoupper($Schema->Name());
    }

    # return sources to caller
    return $Sources;
}

/**
* Retrieve list of schemas corresponding to each source.
* @param int $AvailableSources List of available sources.
* @return array Array keyed by SourceId as returned by
* GetAvailableSources(), where values are arrays of relevant
* SchemaIds.
*/
function GetSourceSchemas($AvailableSources)
{
    $Result = array();

    foreach ($AvailableSources as $Id => $SourceName)
    {
        if ($Id >= 0)
        {
            # if result was a folder, iterate over all the folder
            # Items and collect their SchemaIds
            $Folder = new Folder($Id);

            $FolderSchemas = array();
            foreach ($Folder->GetItemIds() as $ItemId)
            {
                $Resource = new Resource($ItemId);
                $FolderSchemas[$Resource->SchemaId()] = TRUE;
            }

            $Result[$Id] = array_keys($FolderSchemas);
        }
        else
        {
            # otherwise result was a schema, and it just contains itself
            $Result[$Id] = array( -($Id+1) );
        }

    }
    return $Result;
}

/**
* Retrieve list of resource folders that should not be used for export.
* @param array $AvailableSources Available folders of resources to export.
* @return array Array with Folder names for the values and Folder IDs
*       for the index.
*/
function GetDisabledSources($AvailableSources)
{
    # start out assuming no sources will be disabled
    $DisabledSources = array();

    # for each available source
    foreach ($AvailableSources as $Id => $SourceName)
    {
        # if source is a folder
        if ($Id >= 0)
        {
            # if folder has no resources
            $Folder = new Folder($Id);
            if ($Folder->GetItemCount() == 0)
            {
                # add source to disabled list
                $DisabledSources[$Id] = $SourceName;
            }
        }
    }

    # return list of disabled sources to caller
    return $DisabledSources;
}


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

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

$Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
$UserId = $GLOBALS["G_User"]->Id();

$H_ErrorList = new ErrorList();

# determine which action we are currently taking
if (GetFormValue("F_Submit") == "Cancel")
{
    $GLOBALS["AF"]->SetJumpToPage("SysAdmin");
    return;
}
elseif (GetFormValue("F_Submit") == "Export")
{
    $H_Action = "EXPORT";
}
else
{
    $H_Action = "SETUP";
}

# if we are at the data export stage
if ($H_Action == "EXPORT")
{
    # retrieve ID of folder with resources to be exported
    $SourceFolderId = isset($_POST["F_ResourceSource"]) ?
        $_POST["F_ResourceSource"] : NULL;

    # retrieve and check list of metadata fields to export
    $FieldIds = NULL;

    # iterate over all fields in all schemas, checking each to see if
    # it should be included in the export
    foreach (MetadataSchema::GetAllSchemas() as $Schema)
    {
        $Fields = $Schema->GetFields();
        foreach ($Fields as $Field)
        {
            if (array_key_exists("F_ExportField_".$Field->Id(), $_POST))
            {
                $FieldIds[] = $Field->Id();
            }
        }
    }

    if ($FieldIds === NULL)
    {
        $H_ErrorList->AddMessage(
                "No metadata fields were selected for export.",
                "F_ExportField");
    }
    else
    {
        # save list of selected fields
        $IdLists = $Plugin->ConfigSetting("SelectedFieldIdLists");
        $IdLists[$UserId] = $FieldIds;
        $Plugin->ConfigSetting("SelectedFieldIdLists", $IdLists);
    }

    # retrieve and check export format
    $Format = $_POST["F_Format"];
    if (!$Plugin->IsRegisteredFormat($Format))
    {
        $H_ErrorList->AddMessage(
                "Export format was not recognized.",
                "F_Format");
    }
    else
    {
        $Formats = $Plugin->ConfigSetting("SelectedFormats");
        $Formats[$UserId] = $Format;
        $Plugin->ConfigSetting("SelectedFormats", $Formats);
    }

    # retrieve and save export format parameters
    $Formats = $Plugin->GetFormats();
    $FormatParameters = $Plugin->GetExportParameters();
    $FormatParameterValues = $Plugin->ConfigSetting("FormatParameterValues");
    foreach ($FormatParameters as $FormatName => $FormatParams)
    {
        if (count($FormatParams))
        {
            if (!array_key_exists($FormatName, $FormatParameterValues))
                    {  $FormatParameterValues[$FormatName] = array();  }
            $CfgUI = new ConfigSettingsUI($FormatParams,
                    $FormatParameterValues[$FormatName], $FormatName);
            $FormatParameterValues[$FormatName] = $CfgUI->GetNewSettingsFromForm();
        }
    }
    $Plugin->ConfigSetting("FormatParameterValues", $FormatParameterValues);

    # if errors were found
    if ($H_ErrorList->HasErrors())
    {
        # switch to setup mode
        $H_Action = "SETUP";
    }
    else
    {
        # export data
        $H_ExportedResourceCount = $Plugin->ExportData(
                $Format, $SourceFolderId, $FieldIds,
                isset($FormatParameterValues[$Format])
                        ? $FormatParameterValues[$Format]
                        : array());

        # if export succeeded
        if ($H_ExportedResourceCount !== NULL)
        {
            # set values for display in HTML
            $H_ExportedFileName = $Plugin->LastExportFileName();
            $H_ExportedFileSecret = $Plugin->LastExportFileSecret();
        }
        else
        {
            # retrieve error messages
            $Errors = $Plugin->LastExportErrorMessages();
            foreach ($Errors as $ErrMsg)
            {
                $H_ErrorList->AddMessage($ErrMsg);
            }

            # switch to setup mode
            $H_Action = "SETUP";
        }
    }
}

# if we are at the export setup stage
if ($H_Action == "SETUP")
{
    $H_AvailableSources = GetAvailableSources();
    $H_SourceToSchemaMap = GetSourceSchemas($H_AvailableSources);
    $H_DisabledSources = GetDisabledSources($H_AvailableSources);

    $H_SelectedSource = GetFormValue("F_ResourceSource");
    if (is_null($H_SelectedSource))
    {
        # if folders is enabled, use the current user's selected folder
        # otherwise use the first available source
        if ($GLOBALS["G_PluginManager"]->PluginEnabled("Folders"))
        {
            $FFactory = new Folders_FolderFactory($GLOBALS["G_User"]->Id());
            $H_SelectedSource = $FFactory->GetSelectedFolder()->Id();
        }
        else
        {
            $PossibleValueIds = array_keys($H_AvailableSources);
            $H_SelectedSource = reset($PossibleValueIds);
        }
    }

    # construct list of all possible fields
    $H_SchemaNames = array();
    foreach (MetadataSchema::GetAllSchemas() as $SchemaId => $Schema)
    {
        $H_AvailableFields[$SchemaId] = $Schema->GetFields(
            NULL, MetadataSchema::MDFORDER_ALPHABETICAL);
        $H_SchemaNames[$SchemaId] = $Schema->Name();
    }

    $IdLists = $Plugin->ConfigSetting("SelectedFieldIdLists");
    $H_SelectedFieldIds = (count($IdLists) && array_key_exists($UserId, $IdLists))
            ? $IdLists[$UserId] : array();
    $H_ExportedDataTypes = $Plugin->GetExportedDataTypes();

    # if no metadata fields selected
    if (!count($H_SelectedFieldIds))
    {
        # select standard fields
        $StandardFieldNames = array(
                "Title",
                "Description",
                "Url",
                );
        foreach ($StandardFieldNames as $Name)
        {
            $Id = $Schema->GetFieldIdByMappedName($Name);
            if ($Id !== NULL) {  $H_SelectedFieldIds[] = $Id;  }
        }
    }

    # retrieve values for format list
    $H_AvailableFormats = $Plugin->GetFormats();
    $SelectedFormats = $Plugin->ConfigSetting("SelectedFormats");
    $DefaultFormat = count($H_AvailableFormats) ? $H_AvailableFormats[0] : NULL;
    $H_SelectedFormat = (count($SelectedFormats)
            && array_key_exists($UserId, $SelectedFormats))
            ? $SelectedFormats[$UserId] : $DefaultFormat;
    $H_FormatParameters = $Plugin->GetExportParameters();
    $H_FormatParameterValues = $Plugin->ConfigSetting("FormatParameterValues");
}
