<?php
  /**
   * phpaga
   *
   * file upload
   *
   * Upload a file, store it, and create a records that associates the
   * file to an internal object (for example a project, a task, a
   * company, a person, ...)
   *
   * @author Florian Lanthaler <florian@phpaga.net>
   * @version $Id: upload.php 857 2007-09-19 20:12:30Z 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.
   */

include_once("./config.php");

if (PHPAGA_UPLOADS_DISABLED) {
    phpaga_error(_("File uploads are disabled."));
    exit;
}

$status = null;
$err = false;
$numfiles = 0;

if (!isset($_SESSION["auth_user"]["pe_id"]) || !strlen($_SESSION["auth_user"]["pe_id"])) {
    phpaga_error(_("Invalid user."));
    exit;
}

$fileinfo = array("pe_id" => $_SESSION["auth_user"]["pe_id"],
                  "file_original_name" => null,
                  "file_local_name" => null,
                  "file_rel_type" => null,
                  "file_rel_id" => null,
                  "file_mimetype" => null);

if (!isset($_REQUEST["file_rel_type"]) || !strlen($_REQUEST["file_rel_type"])) {
    phpaga_error(_("Invalid file relation type."));
    exit;
}

if (!isset($_REQUEST["file_rel_id"]) || !is_numeric($_REQUEST["file_rel_id"])) {
    phpaga_error(_("Invalid file relation ID."));
    exit;
}

$fileinfo["file_rel_type"] = $_REQUEST["file_rel_type"];
$fileinfo["file_rel_id"] = $_REQUEST["file_rel_id"];

switch ($fileinfo["file_rel_type"])
{
    case PHPAGA_RELTYPE_PROJECT:

        $ismember = phpaga_project_is_member($fileinfo["file_rel_id"], $_SESSION["auth_user"]["pe_id"]);

        if (!$ismember) {
            phpaga_error(_("Only project members are allowed to upload files to this project."));
            exit;
        }

    default:
        break;
}

if (!isset($_FILES['upfiles']) || !count($_FILES['upfiles'])) {
    phpaga_error(_("No file(s) to be uploaded."));
    exit;
}

$dest_dir = PHPAGA_FILEPATH.$fileinfo["file_rel_type"]."/".$fileinfo["file_rel_id"];

if (!is_dir(PHPAGA_FILEPATH))
    $status = sprintf(_("%s: The directory does not exist"), PHPAGA_FILEPATH);

elseif (!is_dir(PHPAGA_FILEPATH.$fileinfo["file_rel_type"]) && !mkdir(PHPAGA_FILEPATH.$fileinfo["file_rel_type"]))
$status = sprintf(_("%s: The directory does not exist and can't be created"), PHPAGA_FILEPATH.$fileinfo["file_rel_type"]);

elseif (!is_dir($dest_dir) && !mkdir($dest_dir))
$status = sprintf(_("%s: The directory does not exist and can't be created"), $dest_dir);

elseif (!is_writable($dest_dir))
$status = sprintf(_("%s: The directory is not writable"), $dest_dir);

if (strlen($status)) {
    phpaga_error($status);
    exit;
}

foreach ($_FILES['upfiles']['error'] as $fid => $ferror) {

    if ((!$ferror == UPLOAD_ERR_OK) && (!$ferror == UPLOAD_ERR_NO_FILE)) {

        $err = true;

        phpaga_error(sprintf(_("An error happened while trying to upload the file %s: %s"),
                             $_FILES['upfiles']['name'][$fid],
                             phpaga_files_getuploadstatusmessage($ferror)));
    } else if($ferror == UPLOAD_ERR_OK) {

        $t_p = pathinfo($_FILES['upfiles']['name'][$fid]);
        $dest_name = md5(uniqid()).'.'.$t_p['extension'];

        if (!move_uploaded_file($_FILES['upfiles']['tmp_name'][$fid], $dest_dir."/".$dest_name)) {
            $err = true;
            phpaga_error(sprintf(_("An error happened while trying to upload the file %s: %s"),
                                 $_FILES['upfiles']['name'][$fid],
                                 $dest_name->getMessage()));
        } else {
            $fileinfo["file_local_name"] = $dest_name;
            $fileinfo["file_original_name"] = $_FILES['upfiles']['name'][$fid];
            $fileinfo["file_mimetype"] = $_FILES['upfiles']['type'][$fid];

            $result = phpaga_files_add($fileinfo);

            if (PhPagaError::isError($result)) {
                $err = true;
                $result->printMessage();
            } else
                $numfiles++;
        }
    }
}

if (!$numfiles) {
    phpaga_error(_("No file(s) have been successfully uploaded."));
    exit;
}

if (!$err) {
    if (isset($_REQUEST["returl"]) && strlen($_REQUEST["returl"]))
        header("Location: ".rawurldecode($_REQUEST["returl"]));
    else
        phpaga_message(_("File added"), _("The file has been added"));
}

?>