<?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 637 2005-09-20 23:15:17Z worf $
   *
   * 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");
require_once('HTTP/Upload.php');

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

$status = null;

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 = false;
    phpaga_project_is_member($fileinfo["file_rel_id"], $_SESSION["auth_user"]["pe_id"], $ismember);

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

default:
    break;

}


$upload = new http_upload('en');
$file = $upload->getFiles("upfile");

if ($file->isMissing()) {
    phpaga_error(_("No file to be uploaded"));
    exit;
}

if (PEAR::isError($file))
    $status = sprintf(_("An error happened while trying to upload the file: %s"),
                      $file->getMessage());
else
{

    $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);

    else
    {

        if ($file->isError()) {
            $status = sprintf(_("An error happened while trying to upload the file: %s"),
                              $file->errorMsg());
        }
        else if ($file->isValid())
        {
            $file->setName('uniq');


            $dest_name = $file->moveTo($dest_dir);

            if (PEAR::isError($dest_name)) {
                $status = sprintf(_("An error happened while trying to upload the file: %s"),
                                  $dest_name->getMessage());
            }
            else
            {
                $fileinfo["file_local_name"] = $dest_name;
                $fileinfo["file_original_name"] = $file->getProp('real');
                $fileinfo["file_mimetype"] = $file->getProp('type');
            }
        }
    }
}


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

$result = phpaga_files_add($fileinfo);

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

?>
