<?PHP
#
#   FILE:  ConvertImageFiles.php
#
#   FUNCTIONS PROVIDED:
#
#   FUNCTIONS EXPECTED:
#       None
#
#   Part of the Scout Portal Toolkit
#   Copyright 2001 Internet Scout Project
#   http://scout.cs.wisc.edu
#

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


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

# function to get list of matching files
function ListDir($DirPath, $Pattern)
{
    static $ResultArray = array();

    $Handle = opendir($DirPath);
    while (false !== ($File = readdir($Handle)))
    {
        if ($File == '.' || $File == '..')
            continue;
        if (is_dir($DirPath.$File))
            continue;
        else if (preg_match($Pattern, $File))
            $ResultArray[]=$DirPath.$File;
    }
    closedir($Handle);
    return $ResultArray;
}

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


function ConvertImageFiles()
{
    global $ErrorMessageList;
    global $_SERVER;

    $Success = true;
    $DB = new Database();
    $Schema = new MetadataSchema();

    # open import file for reading
    $ScriptFileName = $_SERVER['PATH_TRANSLATED'];

    $InputPath = substr($ScriptFileName, 0, strrpos($ScriptFileName, '/')).
        "/ImageStorage/";

    $ImagePaths = ListDir($InputPath, "/^Img*/");

    # create new ImageId field in Resources for each Image field
    $Fields = $Schema->GetFields(MetadataSchema::MDFTYPE_IMAGE);
    foreach ($Fields as $Field)
    {
        $DBFieldName = $Field->DBFieldName();

        # add field to Resources
        $Query = "ALTER TABLE Resources ADD COLUMN ".$DBFieldName.
                " INT DEFAULT 0";

        echo "AlterQuery = $Query<br>";
#        $DB->Query($Query);
    }

    # init ImageId
    $ImageId = 1;

    # walk each image file
    foreach ($ImagePaths as $ImagePath)
    {
        $ImageName = basename($ImagePath);
        $PreviewName = str_replace("Img", "Preview", $ImageName);
        $ThumbName = str_replace("Img", "Thumb", $ImageName);

        $ImageExt = array_pop(explode('.', $ImageName));
        $PreviewExt = array_pop(explode('.', $PreviewName));
        $ThumbExt = array_pop(explode('.', $ThumbName));

        $ThumbPath = $InputPath."Thumbnails/".$ThumbName;
        $PreviewPath = $InputPath."Previews/".$PreviewName;

        echo "ImagePath = $ImagePath<br>";
        echo "PreviewPath = $PreviewPath<br>";
        echo "ThumbPath = $ThumbPath<br>";

        # create new file names
        $NewUrl = $InputPath."Img--".sprintf("%08d", $ImageId).
                        ".".$ImageExt;
        $NewPreview = $InputPath."Previews/Preview--".sprintf("%08d", $ImageId).
                        ".".$PreviewExt;
        $NewThumb = $InputPath."Thumbnails/Thumb--".sprintf("%08d", $ImageId).
                        ".".$ThumbExt;

        if (file_exists($ImagePath))
            $Image = new Image($ImagePath);
        else
        {
            $ErrorMessageList[] = "Image doesn't exist: $ImagePath<br>";
            $Success = false;
        }

        if (file_exists($PreviewPath))
            $Preview = new Image($PreviewPath);
        # no preview image, so create new SPT image which will create Preview
        else
        {
    #        $NewImage = new SPTImage($ImagePath);
            $ErrorMessageList[] = "Preview image doesn't exist: $PreviewPath<br>";
            $Success = false;
        }

        if (file_exists($ThumbPath))
            $Thumb = new Image($ThumbPath);
        # no preview image, so create new SPT image which will create Thumbnail
        else
        {
    #        $NewImage = new SPTImage($ImagePath);
            $ErrorMessageList[] = "Thumbnail Image doesn't exist: $ThumbPath<br>";
            $Success = false;
        }

        echo "ImageStatus=".$Image->Status()."<br>";
        echo "PreviewStatus=".$Preview->Status()."<br>";
        echo "ThumbStatus=".$Thumb->Status()."<br>";

        echo "NewUrl=$NewUrl<br>";
        echo "NewPreview=$NewPreview<br>";
        echo "NewThumb=$NewThumb<br>";

        echo "ImageName = $ImageName<br>";

#        echo "List of missing executables:<br>";
#        $MissingExecutables = $Image->MissingExternalExecutables();
#        foreach ($MissingExecutables as $Missing)
#            echo $Missing."<br>";

        list($ResourceId, $FieldId) = sscanf($ImageName, "Img--%d--%d");

        echo "ResourceId=$ResourceId, FieldId=$FieldId<br>";

        # skip converted files
        if (is_null($FieldId) || empty($FieldId) || !is_numeric($FieldId))
            continue;

        # access Resource object
        $Resource = new Resource($ResourceId);
        $Field = $Schema->GetField($FieldId);
        $DBFieldName = $Field->DBFieldName();
#        $AltText = $Resource->Get($FieldName);
#        $Format = $Resource->Get($FieldName."Format");

        $query = "Select $DBFieldName"."AltText from Resources ".
                "WHERE ResourceId=$ResourceId";
        $query1 = "Select $DBFieldName"."Format from Resources ".
                "WHERE ResourceId=$ResourceId";

        echo "query=$query<br>query1=$query1<br>";

        # get alttext and format directly from Resources
        $AltText = $DB->Query("Select $DBFieldName"."AltText from Resources ".
                "WHERE ResourceId=$ResourceId", $DBFieldName."AltText");
        $Format = $DB->Query("Select $DBFieldName"."Format from Resources ".
                "WHERE ResourceId=$ResourceId", $DBFieldName."Format");

        echo "DBFieldName=$DBFieldName, AltText=$AltText, Format=$Format<br>";

        # set ImageId for Resource
        $Query = "Update Resources set ".$DBFieldName." = $ImageId where ".
            "ResourceId = ".$ResourceId;

        echo "Query=$Query<br>";
#        $DB->Query($Query);

        echo "ImageX=".$Image->XSize().", Type=".$Image->Type()."<br>";
        echo "ImageY=".$Image->YSize().", Type=".$Image->Type()."<br>";
        echo "PreviewX=".$Preview->XSize().", Type=".$Preview->Type()."<br>";
        echo "PreviewY=".$Preview->YSize().", Type=".$Preview->Type()."<br>";
        echo "ThumbX=".$Thumb->XSize().", Type=".$Thumb->Type()."<br>";
        echo "ThumbY=".$Thumb->YSize().", Type=".$Thumb->Type()."<br>";

        # create Image record
        $Query = "INSERT INTO Images (ImageId, Format, AltText, Width, Height, ".
                "PreviewWidth, PreviewHeight, ThumbnailWidth, ThumbnailHeight) VALUES (".
                "$ImageId, \"$Format\", \"$AltText\", ".$Image->XSize().", ".
                $Image->YSize().", ".$Preview->XSize().", ".$Preview->YSize().", ".
                $Thumb->XSize().", ".$Thumb->YSize().")";

        echo "Query = $Query<br>";

#        $DB->Query($Query);

        # rename the old files to the new files
#        if (rename($ImagePath, $NewUrl) == false)
#        {
#            $ErrorMessageList[] = "Rename Failed: Src=$ImagePath, Dst=$NewUrl<br>";
#            $Success = false;
#        }
#        if (rename($PreviewPath, $NewPreview) == false)
#        {
#            $ErrorMessageList[] = "Rename Failed: Src=$PreviewPath, Dst=$NewPreview<br.";
#            $Success = false;
#        }
#        if (rename($ThumbPath, $NewThumb) == false)
#        {
#            $ErrorMessageList[] = "Rename Failed: Src=$ThumbPath, Dst=$NewThumb<br>";
#            $Success = false;
#        }
        $ImageId++;
    }

    # now drop the AltText and Format fields for each StillImage field
    $Fields = $Schema->GetFields(MetadataSchema::MDFTYPE_IMAGE);
    foreach ($Fields as $Field)
    {
        $DBFieldName = $Field->DBFieldName();
        echo "dropping column $DBFieldName...<br>";
#        $DB->Query("ALTER TABLE Resources DROP COLUMN ".$DBFieldName."AltText");
#        $DB->Query("ALTER TABLE Resources DROP COLUMN ".$DBFieldName."Format");
    }
    return $Success;
}

# non-standard global variables
global $ErrorMessageList;

$ErrorMessageList = array();

ConvertImageFiles();

foreach ($ErrorMessageList as $Error)
{
    echo "ERROR: $Error";
}
