<?php
/**
 * phpaga
 *
 * File management functionality.
 *
 * This file contains the necessary routines to manage uploaded files.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: files.php 743 2006-09-27 21:19:50Z florian $
 *
 * Copyright (c) 2005, Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


/**
 * Adds a new file to the database.
 *
 * @param  array   $user     Array containing file information.
 *
 * @return int     $result   A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_files_add ($file)
{

    if (!isset($file["file_original_name"]) || !strlen($file["file_original_name"])
        || !isset($file["file_local_name"]) || !strlen($file["file_local_name"])
        || !isset($file["file_rel_type"]) || !is_numeric($file["file_rel_type"])
        || !isset($file["file_rel_id"]) || !is_numeric($file["file_rel_id"]))

        return PHPAGA_ERR_INVALID_PARAMTYPE;

    if (!isset($file["pe_id"]) || !is_numeric($file["pe_id"]))
        $file["pe_id"] = $_SESSION["auth_user"]["pe_id"];

    phpaga_db_connect($db);

    $fields = array("file_id"=> $db->nextId("files_file_id"),
                    "pe_id" => $file["pe_id"],
                    "file_original_name" => $file["file_original_name"],
                    "file_local_name" => $file["file_local_name"],
                    "file_rel_type" => $file["file_rel_type"],
                    "file_rel_id" => $file["file_rel_id"],
                    "file_mimetype" => $file["file_mimetype"]
        );

    $result = $db->autoExecute("files", $fields, DB_AUTOQUERY_INSERT);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}


/**
 * Get a list with information about all files that belong to a
 * certain relation.
 *
 * @param  int     $file_rel_type   Type of the related object
 * @param  int     $file_rel_id     ID of the related object
 * @param  array   &$files          File(s) information
 *
 * @return int     $result          A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_files_getAllRel ($file_rel_type, $file_rel_id, &$files)
{

    global $phpaga_preview_types;

    $files = array();

    if (!isset($file_rel_type) || !is_numeric($file_rel_type)
        || !isset($file_rel_id) || !is_numeric($file_rel_id))

        return PHPAGA_ERR_INVALID_PARAMTYPE;

    phpaga_db_connect($db);

    if (PHPAGA_DB_SYSTEM == "pgsql")
        $t_file_added = "to_char(file_added, 'yyyy-mm-dd hh24:mi:ss'::text) as file_added";
    else
        $t_file_added = "file_added";

    $query = "SELECT file_id, ".$t_file_added.", files.pe_id, file_original_name, ".
        "file_local_name, file_mimetype, persons.pe_lastname, persons.pe_firstname ".
        "FROM files ".
        "LEFT JOIN persons ON persons.pe_id = files.pe_id ".
        "WHERE file_rel_type = ".$db->quoteSmart($file_rel_type).
        " AND file_rel_id = ".$db->quoteSmart($file_rel_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    while ($qrow = $result->fetchRow())
    {

        $qrow["pe_person"] =
            phpaga_persons_formatname($qrow["pe_lastname"],
                                      $qrow["pe_firstname"]);

        if (in_array($qrow["file_mimetype"], $phpaga_preview_types))
            $qrow["preview"] = true;
        else
            $qrow["preview"] = false;

        $files[] = $qrow;
    }

    return PHPAGA_ERR_NONE;
}


/**
 * Get the information about a specific file.
 *
 * @param  int     $file_id         File ID
 * @param  array   &$file           File information
 *
 * @return int     $result          A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_files_getInfo ($file_id, &$file)
{

    $file = array();

    if (!isset($file_id) || !is_numeric($file_id))
        return PHPAGA_ERR_INVALID_PARAMTYPE;

    phpaga_db_connect($db);

    if (PHPAGA_DB_SYSTEM == "pgsql")
        $t_file_added = "to_char(file_added, 'yyyy-mm-dd hh24:mi:ss'::text) as file_added";
    else
        $t_file_added = "file_added";

    $query = "SELECT file_id, ".$t_file_added.", files.pe_id, file_original_name, ".
        "file_local_name, file_mimetype, persons.pe_lastname, persons.pe_firstname, ".
        "file_rel_type, file_rel_id ".
        "FROM files ".
        "LEFT JOIN persons ON persons.pe_id = files.pe_id ".
        "WHERE file_id = ".$db->quoteSmart($file_id);

    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($result->numRows() < 1)
        return PHPAGA_ERR_DB_NO_ROWS;

    while ($qrow = $result->fetchRow())
    {
        $qrow["pe_person"] =
            phpaga_persons_formatname($qrow["pe_lastname"],
                                      $qrow["pe_firstname"]);

        $file = $qrow;
    }

    $result->free();
    return PHPAGA_ERR_NONE;
}


/**
 * Deletes a file both from the file system and from the database.
 *
 * @param int    $file_id    File ID
 *
 * @return int   $result     A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.3
 */

function phpaga_files_delete ($file_id)
{

    if (!isset($file_id) || !is_numeric($file_id))
        return PHPAGA_ERR_INVALID_PARAMTYPE;

    $file = array();

    $result = phpaga_files_getInfo($file_id, $file);

    if ($result == PHPAGA_ERR_DB_NO_ROWS)
        return PHPAGA_ERR_NONE;

    if ($result != PHPAGA_ERR_NONE)
        return $result;

    if (file_exists(PHPAGA_FILEPATH.$file["file_rel_type"]."/".$file["file_rel_id"]."/".$file["file_local_name"]) &&
        !unlink(PHPAGA_FILEPATH.$file["file_rel_type"]."/".$file["file_rel_id"]."/".$file["file_local_name"]))
        return PHPAGA_ERR_FILE_REMOVE;

    phpaga_db_connect($db);

    $query = "DELETE FROM files WHERE file_id = ".$db->quoteSmart($file_id);
    $result = $db->query($query);

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    return PHPAGA_ERR_NONE;

}

?>