<?PHP

$GLOBALS["G_ErrMsgs"] = SiteUpgrade311_PerformUpgrade();

/**
* Perform all of the site upgrades for 3.1.1.
* @return Returns NULL on success and an eror message if an error occurs.
*/
function SiteUpgrade311_PerformUpgrade()
{
    try
    {
        Msg(1, "Upgrading field ordering for Resource schema...");
        SiteUpgrade311_UpgradeFieldOrder();

        Msg(1, "Cleaning metadata field orders for Resource schema...");
        SiteUpgrade311_CleanMetadataFieldOrders();
    }

    catch (Exception $Exception)
    {
        return array($Exception->getMessage(),
                "Exception Trace:<br/><pre>"
                        .$Exception->getTraceAsString()."</pre>");
    }
}

/**
* Clean up Edit and Display orders for Resource schema.
*/
function SiteUpgrade311_CleanMetadataFieldOrders()
{
    $Schema = new MetadataSchema();

    foreach(array("GetEditOrder", "GetDisplayOrder") as $Ofn)
    {
        SiteUpgrade311_ProcessFieldOrder( $Schema->$Ofn() );
    }
}

/**
* Iterate through MetadataFieldOrders and groups, removing Fields that
* came from other schemas.
*/
function SiteUpgrade311_ProcessFieldOrder($Group)
{
    $Items = ($Group instanceof MetadataFieldGroup) ?
        $Group->GetFields() :
        $Group->GetItems() ;

    foreach ($Items as $Item)
    {
        if ($Item instanceof MetadataField)
        {
            if ($Item->SchemaId() != MetadataSchema::SCHEMAID_DEFAULT)
            {
                $Group->RemoveItem($Item->Id(), "MetadataField");
            }
        }
        elseif ($Item instanceof MetadataFieldGroup)
        {
            SiteUpgrade311_ProcessFieldOrder($Item);
        }
    }
}

/**
* Make sure each schema has a field order defined.
*/
function SiteUpgrade311_UpgradeFieldOrder()
{
    $DB = new Database();

    foreach (MetadataSchema::GetAllSchemas() as $Schema)
    {
        foreach (array(MetadataSchema::ORDER_DISPLAY_NAME,
                       MetadataSchema::ORDER_EDIT_NAME) as $Name)
        {
            # try to fetch an existing order
            $Order = MetadataFieldOrder::GetOrderForSchema($Schema, $Name);

            # if the order doesn't exist
            if (is_null($Order))
            {
                # see if we had a folder for the order stored for the sysconfig
                $OldId = ($Name == MetadataSchema::ORDER_EDIT_NAME) ?
                    $GLOBALS["SysConfig"]->FieldEditFolder() :
                    $GLOBALS["SysConfig"]->FieldDisplayFolder() ;

                # if the older version of MetadataFieldOrder was in use
                if ($OldId && $Schema->Id() == MetadataSchema::SCHEMAID_DEFAULT)
                {
                    # add an entry for the existing folder
                    $DB->Query(
                        "INSERT INTO MetadataFieldOrders "
                        ."SET SchemaId = '".addslashes(MetadataSchema::SCHEMAID_DEFAULT)."', "
                        ."OrderId = '".addslashes($OldId)."',"
                        ."OrderName = '".addslashes($Name)."'");
                }
                else
                {
                    $UpgradeOrder = array();

                    # temporarily suppress errors
                    $Setting = Database::DisplayQueryErrors();
                    Database::DisplayQueryErrors(FALSE);

                    # see if the old columns exist
                    $Handle = $DB->Query(
                        "SELECT EditingOrderPosition "
                        ."FROM MetadataFields LIMIT 1");

                    # restore the earlier error setting
                    Database::DisplayQueryErrors($Setting);

                    if ($Handle !== FALSE)
                    {
                        # determine which column to use for ordering
                        $Column = ($Name == MetadataSchema::ORDER_DISPLAY_NAME)
                            ? "DisplayOrderPosition" : "EditingOrderPosition";

                        # query for the fields in their proper order
                        $DB->Query(
                            "SELECT FieldId "
                            ."FROM MetadataFields "
                            ."WHERE FieldId > 0 "
                            ."ORDER BY ".$Column." ASC");

                        # use the order from the DB
                        $UpgradeOrder = $DB->FetchColumn("FieldId");
                    }

                    # otherwise create a new order
                    MetadataFieldOrder::Create(
                        $Schema, $Name, $UpgradeOrder);
                }
            }
        }
    }
}
