<?PHP

#
#   FILE:  FileFactory.php
#
#   Part of the Collection Workflow Integration System
#   Copyright 2007-2009 Edward Almasy and Internet Scout
#   http://scout.wisc.edu
#

/**
* Factory for manipulating File objects.
*/
class FileFactory extends ItemFactory {

    # ---- PUBLIC INTERFACE --------------------------------------------------

    # object constructor
    function FileFactory($FieldId = NULL)
    {
        # set up item factory base class
        $this->ItemFactory("File", "Files", "FileId", "FileName", $FieldId);
    }

    # retrieve all files (names or objects) for specified resource
    # (array index is file IDs)
    function GetFilesForResource($ResourceOrResourceId, $ReturnObjects = TRUE)
    {
        # start out assuming that no files will be found
        $ReturnValue = array();

        # sanitize resource ID or grab it from object
        $ResourceOrResourceId = is_object($ResourceOrResourceId)
                ? $ResourceOrResourceId->Id() : intval($ResourceOrResourceId);

        # retrieve names and IDs of files associated with resource
        $this->DB->Query(
            "SELECT FileId, FileName FROM Files"
            ." WHERE ResourceId = ".$ResourceOrResourceId
            ." AND FieldId"
            .($this->FieldId ? "=".$this->FieldId : ">0"));
        $FileNames = $this->DB->FetchColumn("FileName", "FileId");

        # if files were found
        if (count($FileNames))
        {
            # if caller asked us to return objects
            if ($ReturnObjects)
            {
                # for each file
                foreach ($FileNames as $FileId => $FileName)
                {
                    # create file object and add it to array
                    $ReturnValue[$FileId] = new File($FileId);
                }
            }
            else
            {
                # return array of file names with IDs as index
                $ReturnValue = $FileNames;
            }
        }

        # return resulting array of files or file names to caller
        return $ReturnValue;
    }

    # create copy of File and return to caller
    function Copy($FileToCopy)
    {
        return new File($FileToCopy->GetNameOfStoredFile(),
                $FileToCopy->ResourceId(),
                $FileToCopy->FieldId(),
                $FileToCopy->Name());
    }


    # ---- PRIVATE INTERFACE -------------------------------------------------

}


?>
