<?php
/* $Id: index.php,v 1.54 2003/12/02 14:44:32 k-fish Exp $ */
if(function_exists("revisionInit")) revisionInit("\$Revision: 1.54 $", __FILE__);

$myEnv["module"] = "files";
$myEnv["output"] = "html";

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");

global $appconf;

if (!file_exists(STORE_FOLDER.".htaccess")) {
    $fd = fopen(STORE_FOLDER.".htaccess", "wb");
    fwrite($fd, "Order deny,allow\nDeny from all\n");
    fclose($fd);
}

$action = (isset($_POST['action'])) ? $_POST['action'] : ((isset($_GET['action'])) ? $_GET['action'] : '');
if(isset($_POST['obj']) && $_POST['obj'] == 'category') $action = 'category';

switch ($action) {
 case "category":
     manCategories();
     break;

 case "newform":
     newForm();
     break;

 case "create":
     doCreate();
     break;

 case "editform":
     editForm();
     break;

 case "edit":
     doEdit();
     break;
 
 case "copyform":
 	 copyForm();
	 break;
	 
 case "copy":
 	 doCopy();
	 break;
        
 case "details":
     detailsPage();
     break;

 case "emailfile":
     emailFile();
     break;

 case "delete":
     doDelete();
     break;

 case "specDir":
     specifyFile("dir");
     break;
        
 case "specFile":
     specifyFile("file");
     break;
}

listFiles();
exit();

// =================================================
//                Category Handling
// =================================================

function manCategories() {
    include("./inc/category.class.php");
    $catObj = new Category();
    if (isset($_POST["op"]) && $_POST["op"] == "create"){
	$catObj->opCreate();
    }

    if(isset($_POST["op"]) && $_POST["op"] == "edit"){
	$catObj->opUpdate();
    }
   
    if (isset($_GET["view"]) && $_GET["view"] == "newform") {
	$catObj->viewNewForm();
	exit();
    }

    if (isset($_GET["view"]) && $_GET["view"] == "editform") {
	$id = (int) $_GET["id"];
	$catObj->viewEditForm($id);
	exit();
    }

    if(isset($_GET["view"]) && $_GET["view"] == "details"){
	$id = (int) $_GET["id"];
	$catObj->viewDetails($id);
	exit();
    }

    if(isset($_POST["confirmation_yes"])) {
	$id = (int) $_POST["itemid"];
	$catObj->opDelete($id);
    }
    elseif (isset($_GET["view"]) && $_GET["view"] == "delete"){
	$id = (int) $_GET["id"];
	$catObj->viewDelete($id);
	exit();
    }

    $catObj->viewList();
    exit();
}
// =================================================
//	              Copy File Form
// =================================================
function copyForm() {
    global $smarty, $conn;
    
    $fileId = (int) $_GET['fileId'];
    $sql= getRightsQuery($fileId);
    if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if (checkForFileRight($fileId)) {
	include(INCLUDEPATH . "mSelectBox.class.php");

	$smarty->assign("current_dir_name", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
	$smarty->assign("index_url", "index.php?".SID);
	$smarty->assign("haction", "copy");

	if ($res["type"] == "d") {
	    $smarty->assign("mode", "copydir");
	    $smarty->assign("file_details_header", Lang::getLanguageString("copydir"));
	    $smarty->assign("output", Lang::getLanguageString("emsg_fileisdirectory"));
	}
	else {
	    $smarty->assign("mode", "copyfile");
	    $smarty->assign("file_details_header", Lang::getLanguageString("copyfile"));

	    //now get the contents of the file
	    $mime_types = explode("/", $res["mime_type"]);
	    $file_name = STORE_FOLDER . $res["resides_in"]."-".$res["name"];
	    switch ($mime_types[0]) {
	    case "text":
		$fp = fopen($file_name, "r");
		$content = htmlentities(fread($fp, filesize($file_name)), ENT_QUOTES, $_SESSION['MGW']->charset);
		fclose($fp);
		$smarty->assign("output", '<textarea rows="40" cols="60" name="files[file_content]">'.$content.'</textarea>');
		break;
	    default:
		$smarty->assign("output", Lang::getLanguageString("emsg_editunsupportedfiletype"));
	    }
	}

	$smarty->assign("resides_in", dirSelector(0,$_SESSION["MGW"]->settings["files"]["curr_dir_id"]));

	if($res["owner"] == $_SESSION["MGW"]->userid) {
	    //ok, the current user is the owner of the file
	    $smarty->assign("isowner", true);    
 
	    if(isModuleInstalled('projects')){
		//create a select box for project mapping change
		$sb6 = new mSelectBox("files[projectid]",$res["project"]);
		$sb6->setContentType("sql");
		$sb6->setSQLvalue("project_id");
		$sb6->setSQLcontent("title");
		$sb6->addContent("select project_id, title from mgw_projects order by title");
		$sb6->addOption("0", Lang::getLanguageString("noprojectmapping"), "pre");
		$smarty->assign("projectssb", $sb6->draw()); 
	    }
    
	    //create a select box for category change
	    $sb7 = new mSelectBox("files[categoryid]",$res["category"]);
	    $sb7->setContentType("sql");
	    $sb7->setSQLvalue("id");
	    $sb7->setSQLcontent("name");
	    $sb7->addContent("select id, name from mgw_files_categories order by name");
	    $sb7->addOption("0", Lang::getLanguageString("nocategorymapping"), "pre");
	    $smarty->assign("categoriessb", $sb7->draw()); 
	    
	    //create a select box, for ownerchange
	    $sb = new mSelectBox("files[selectnewowner]");
	    $sb->setContentType("sql");
	    $sb->setSQLvalue("id");
	    $sb->setSQLcontent("name");
	    $constr = $conn->Concat('lastname', "', '",'firstname');
	    $sb->addContent("SELECT *, $constr AS name FROM mgw_users ORDER BY lastname");
	    $smarty->assign("selectnewowner", $sb->draw($res['owner']));

	    //get the current filepermissions of the file
	    $rights = getRightsFromDB($res);

	    // groups
	    foreach ($_SESSION["MGW"]->groups as $group) {
		$g_details = getGroupDetails($group);
		$groups[$group]["name"] = $g_details["name"];
		$groups[$group]["description"] = $g_details["description"];
	    }
	    $smarty->assign("groups", $groups);

	    $res["all_rights"] = array();
	    if($rights['o'] & READ) $res["all_rights"]["readischecked"] = "checked";
	    if($rights['o'] & WRIT) $res["all_rights"]["writischecked"] = "checked";
	    if($rights['o'] & DELE) $res["all_rights"]["deleischecked"] = "checked";
	}

	$smarty->assign("files", $res);    
	$smarty->assign("suname", "post_action");
	$smarty->display("files_copy.tpl"); 
	exit();
    }
    else
	$GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
}

// =================================================
//	              Copy File 
// =================================================
function doCopy(){
    global $smarty, $conn;
    $sql= getRightsQuery($_POST['files']['fileId']);
    if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if (($res['owner'] == $_SESSION['MGW']->userid) || checkForFileRight($res["rights"])){

    include_once('inc/mime/Magic.php');
    if ($_POST["files"]["post_action"] == Lang::getLanguageString("abort")) {
	return;
    }

    extract($_POST['files']);
    $id = $conn->GenID('mgw__seq_files');
    
    if ($file_type == 'f') {
	// if (($file_name != $old_file_name) || ($file_location != $old_file_location)) {
	$temp_file_name = $file_name;
	$c = 0;
	while (file_exists(STORE_FOLDER . "$file_location-$file_name")) {
	    $file_name = "copy".$c."-of-".$temp_file_name;
	    $c++;
	}
			
	if (!file_exists(STORE_FOLDER . "$file_location-$file_name")) { 
	    copy(STORE_FOLDER . "$old_file_location-$old_file_name", STORE_FOLDER . "$file_location-$file_name");
	} else {
	    exit();
	}

	$filesize = filesize(STORE_FOLDER."$file_location-$file_name");
	$mime_type = MIME_Magic::filenameToMIME(STORE_FOLDER."$file_location-$file_name");
	if(stristr($mime_type, $_SESSION['MGW']->settings['files_forbidden_mime'])){
	    $GLOBALS['log']->message(MGW_NOTICE, 'MIME type not allowed, discarding file', __LINE__, __FILE__);
	    unlink(STORE_FOLDER."$file_location-$file_name");
            deleteFile((int) $fileId);
	    return;
	}
    }
    else{
	$filesize = 0;
	$mime_type = '';
    }

    $sql="SELECT owner FROM mgw_files WHERE id=".(int)$fileId;
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $res = $res->FetchRow();

    $all_rights = (int)getRightsFromForm($all_rights);
    if($res["owner"] == $_SESSION["MGW"]->userid){
	if($selectnewowner != 0)
	    $res["owner"] = $selectnewowner;

	performGroupRights($id, $_POST['grouprights']);

	$sql="INSERT INTO mgw_files (id, type, resides_in, project, category, owner, name, size, mime_type, owner_rights, all_rights, created, modified) VALUES ($id, ".$conn->QMagic($_POST['files']['file_type']).", '".(int)$file_location."', '".(int)$_POST['files']['projectid']."', '".(int)$_POST['files']['categoryid']."','".$res['owner']."', ".$conn->QMagic($file_name).", '$filesize', '$mime_type', 7, $all_rights, ".$conn->DBTimeStamp(time()).", ".$conn->DBTimeStamp(time()).")";
    	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    }
    else{
	$sql="INSERT INTO mgw_files (id, type, resides_in, project, category, owner, name, size, mime_type, owner_rights, all_rights, created, modified) VALUES ($id, ".$conn->QMagic($_POST['files']['file_type']).", '".(int)$file_location."', '".(int)$_POST['files']['projectid']."', '".(int)$_POST['files']['categoryid']."','".$_SESSION['MGW']->userid."', ".$conn->QMagic($file_name).", $filesize, '$mime_type', 7, $all_rights, ".$conn->DBTimeStamp(time()).", ".$conn->DBTimeStamp(time()).")";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
    return;
}
    else
      $GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
}

// =================================================
//	              New File Form
// =================================================
function newForm() {
    global $smarty;
    include(INCLUDEPATH . "mSelectBox.class.php");
    queryRights2('root_modules_files_files_write');

    $smarty->assign("suname","create");
    $smarty->assign("suclass","submit");
    $smarty->assign("index_url", "index.php?".SID);

    $smarty->assign("filetypes", array("f" => Lang::getLanguageString("file"), "d" => Lang::getLanguageString("directory")));
    $smarty->assign("resides_in", dirSelector(0,$_SESSION["MGW"]->settings["files"]["curr_dir_id"]));
    $smarty->assign("haction","create");

    // groups
    foreach ($_SESSION["MGW"]->groups as $group) {
       $g_details = getGroupDetails($group);
       $groups[$group]["name"] = $g_details["name"];
       $groups[$group]["description"] = $g_details["description"];
    }
    $smarty->assign("groups", $groups);

    if(isModuleInstalled('projects')){
	// create a select box for Project mapping	
	$sb6 = new mSelectBox("files[projectid]");
	$sb6->setContentType("sql");
	$sb6->setSQLvalue("project_id");
	$sb6->setSQLcontent("title");
	$sb6->addContent("select project_id, title from mgw_projects order by title");
	$sb6->addOption("0", Lang::getLanguageString("noprojectmapping"), "pre");
	$smarty->assign("projectssb", $sb6->draw());
    }

    //create a select box for Category mapping
    $sb7 = new mSelectBox("files[categoryid]");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name");
    $sb7->addContent("select id, name from mgw_files_categories order by name");
    $sb7->addOption("0", Lang::getLanguageString("nocategorymapping"), "pre");
    $smarty->assign("categoriessb", $sb7->draw());

    $smarty->display('files_new.tpl');
    exit();
}

// =================================================
//              Create file
// =================================================
function doCreate(){
    global $smarty, $conn;
    include_once('inc/mime/Magic.php');
    queryRights2('root_modules_files_files_write');

    if ($_POST['files']['create'] == Lang::getLanguageString("abort")) {
        return;
    }

    if (!checkForFileRight($_POST['files']['file_location'], WRIT)) {
    	$GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
    }

    $id = mgw_genID('mgw__seq_files');
    $file_location = (int) $_POST['files']['file_location'];

    if ($_POST['files']['file_name'] == "") {
        $file_name = $_FILES['userfile']['name'];
    }
    else{
	$file_name = $_POST['files']['file_name'];
    }

    $sql="SELECT COUNT(id) AS fcount FROM mgw_files WHERE name=".$conn->QMagic($file_name)." AND resides_in=".(int)$file_location;
    if(!($res = $conn->GetRow($sql)) === true) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if($res['fcount'] != 0){
	$GLOBALS['notify']->message(Lang::getLanguageString('emsg_fileexists'), NOTIFY_SCREEN);
	return;
    }
    
    if ($_POST['files']['file_type'] == "f") {
	if ($_POST['files']['file_content'] == "specified") {
	    if(!move_uploaded_file($_FILES['userfile']['tmp_name'], STORE_FOLDER."$file_location-$file_name")){
		switch($_FILES['userfile']['error']){
		case UPLOAD_ERR_INI_SIZE:
		    $GLOBALS['notify']->message(Lang::getLanguageString('emsg_uploaderror1'), NOTIFY_SCREEN);
		    break;
		case UPLOAD_ERR_FORM_SIZE:
		    $GLOBALS['notify']->message(Lang::getLanguageString('emsg_uploaderror2'), NOTIFY_SCREEN);
		    break;
		case UPLOAD_ERR_PARTIAL:
		    $GLOBALS['notify']->message(Lang::getLanguageString('emsg_uploaderror3'), NOTIFY_SCREEN);
		    break;
		case UPLOAD_ERR_NO_FILE:
		    $GLOBALS['notify']->message(Lang::getLanguageString('emsg_uploaderror4'), NOTIFY_SCREEN);
		    break;
		default:
		    $GLOBALS['notify']->message(Lang::getLanguageString('emsg_uploaderror'), NOTIFY_SCREEN);
		}
		return;
	    }
	    $filesize = filesize(STORE_FOLDER."$file_location-$file_name");
	    $mime_type = MIME_Magic::filenameToMIME(STORE_FOLDER."$file_location-$file_name");
	    if(stristr($mime_type, $_SESSION['MGW']->settings['files_forbidden_mime'])){
		$GLOBALS['log']->message(MGW_NOTICE, Lang::getLanguageString('emsg_mimeforbidden'), __LINE__, __FILE__);
		unlink(STORE_FOLDER."$file_location-$file_name");
		return;
	    }
	}
	else {
	    $mime_type = 'text/plain';
	    $file_content = "";
	    $fp = fopen(STORE_FOLDER."$file_location-$file_name", w);
	    fclose($fp);
	    $filesize = filesize(STORE_FOLDER."$file_location-$file_name");
	}
    }
    elseif($_POST['files']['file_type'] == 'd') {
	$mime_type = '';
	$file_content = '';
	$filesize = 0;
    }
    else {
	$GLOBALS['notify']->message(Lang::getLanguageString('emsg_uploaderror'), NOTIFY_SCREEN);
	return;
    }

    $all_rights = (isset($_POST['files']['all_rights'])) ? getRightsFromForm($_POST['files']['all_rights']) : 0;
    $sql="INSERT INTO mgw_files (id, type, resides_in, project, category, owner, name, size, mime_type, owner_rights, all_rights, created, modified) VALUES ($id, ".$conn->QMagic($_POST['files']['file_type']).", '".(int)$file_location."', '".(int)$_POST['files']['projectid']."', '".(int)$_POST['files']['categoryid']."','".(int)$_SESSION["MGW"]->userid."', ".$conn->QMagic($file_name).", $filesize, '$mime_type', 7, $all_rights, ".$conn->DBTimeStamp(time()).", ".$conn->DBTimeStamp(time()).")";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    performGroupRights($id, $_POST['grouprights']);

    return;
}

// =================================================
//              Edit File Details Form
// =================================================
function editForm(){
    global $smarty, $conn;
    //get the info of the file
    $fileId = (int) $_GET['fileId'];

    $sql= getRightsQuery($fileId);
    if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if (checkForFileRight($fileId, WRIT)) {

      include(INCLUDEPATH . "mSelectBox.class.php");    

    $smarty->assign("current_dir_name", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
    $smarty->assign("index_url", "index.php?".SID);
    $smarty->assign("haction", "edit");

    if ($res["type"] == "d") {
	$smarty->assign("mode", "editdir");
	$smarty->assign("file_details_header", Lang::getLanguageString("editdir"));
        $smarty->assign("output", Lang::getLanguageString("emsg_fileisdirectory"));
    }
    else {
	$smarty->assign("mode", "editfile");
	$smarty->assign("file_details_header", Lang::getLanguageString("editfile"));

	//now get the contents of the file
	$mime_types = explode("/", $res["mime_type"]);
	$file_name = STORE_FOLDER . $res["resides_in"]."-".$res["name"];
	switch ($mime_types[0]) {
	case "text":
	    $fp = fopen($file_name, "r");
	    $content = htmlentities(fread($fp, filesize($file_name)), ENT_QUOTES, $_SESSION['MGW']->charset);
	    fclose($fp);
	    $smarty->assign("output", '<textarea rows="40" cols="60" name="files[file_content]">'.$content.'</textarea>');

	    break;
	default:
	    $smarty->assign("output", Lang::getLanguageString("emsg_editunsupportedfiletype"));
	}
    }

    $smarty->assign("resides_in", dirSelector(0,$_SESSION["MGW"]->settings["files"]["curr_dir_id"]));

    if($res["owner"] == $_SESSION["MGW"]->userid) {
	//ok, the current user is the owner of the file
        $smarty->assign("isowner", true);    
 
	if(isModuleInstalled('projects')){
	    //create a select box for project mapping change
	    $sb6 = new mSelectBox("files[projectid]",$res["project"]);
	    $sb6->setContentType("sql");
	    $sb6->setSQLvalue("project_id");
	    $sb6->setSQLcontent("title");
	    $sb6->addContent("select project_id, title from mgw_projects order by title");
	    $sb6->addOption("0", Lang::getLanguageString("noprojectmapping"), "pre");
	    $smarty->assign("projectssb", $sb6->draw());
	    
	    // if the file has a project, show the user a task drop down too.
	    $sb8 = new mSelectBox("files[taskid]",$res["task"]);
	    $sb8->setContentType("sql");
	    $sb8->setSQLvalue("task_id");
	    $sb8->setSQLcontent("title");
	    $sb8->addContent("SELECT task_id, title FROM mgw_projects_tasks ".
	                    "WHERE project_id=".(int)$res["project"]." ORDER BY title");
	    $sb8->addOption("0", Lang::getLanguageString("notaskmapping"), "pre");
	    $smarty->assign("taskssb", $sb8->draw());
	}
    
	//create a select box for category change
	$sb7 = new mSelectBox("files[categoryid]",$res["category"]);
	$sb7->setContentType("sql");
	$sb7->setSQLvalue("id");
	$sb7->setSQLcontent("name");
	$sb7->addContent("select id, name from mgw_files_categories order by name");
	$sb7->addOption("0", Lang::getLanguageString("nocategorymapping"), "pre");
	$smarty->assign("categoriessb", $sb7->draw()); 
	    
	//create a select box, for ownerchange
	$sb = new mSelectBox("files[selectnewowner]");
	$sb->setContentType("sql");
	$sb->setSQLvalue("id");
	$sb->setSQLcontent("name");
	$constr = $conn->Concat('lastname', "', '",'firstname');
	$sb->addContent("SELECT *, $constr AS name FROM mgw_users ORDER BY lastname");
	$smarty->assign("selectnewowner", $sb->draw($res['owner']));

	//get the current filepermissions of the file

	// get rights for each group the user is in
	foreach ($_SESSION["MGW"]->groups as $group) {
	    $g_details = getGroupDetails($group);
            $groups[$group]["name"] = $g_details["name"];
            $groups[$group]["description"] = $g_details["description"];
	    $sql = getRightsQuery4($fileId, $group);
	    $db_rights = $conn->getOne($sql);
	    if (hasRight($db_rights, READ)) $groups[$group]["read"] = "checked";
	    if (hasRight($db_rights, WRIT)) $groups[$group]["writ"] = "checked";
	    if (hasRight($db_rights, DELE)) $groups[$group]["dele"] = "checked";
	}
	$smarty->assign("groups", $groups);	
	
	/*$res["group_rights"] = array();
	if($rights['g'] & READ) $res["group_rights"]["readischecked"] = "checked";
	if($rights['g'] & WRIT) $res["group_rights"]["writischecked"] = "checked";
	if($rights['g'] & DELE) $res["group_rights"]["deleischecked"] = "checked";*/

	$allrights = getRightsFromDB($res);
	$res["all_rights"] = array();
	if($allrights['o'] & READ) $res["all_rights"]["readischecked"] = "checked";
	if($allrights['o'] & WRIT) $res["all_rights"]["writischecked"] = "checked";
	if($allrights['o'] & DELE) $res["all_rights"]["deleischecked"] = "checked";
    }

    $smarty->assign("files", $res);    
    $smarty->assign("suname", "post_action");
    $smarty->display("files_edit.tpl"); 
    exit();
}
    else
      $GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
}

// =================================================
//              Edit file
// =================================================
function doEdit(){
    global $smarty, $conn;

    if (checkForFileRight((int)$_POST['files']['fileId'], WRIT)) {
    include_once('inc/mime/Magic.php');
    if ($_POST["files"]["post_action"] == Lang::getLanguageString("abort")) {
	return;
    }

    extract($_POST['files']);

    if ($file_type == 'f') {
	if (($file_name != $old_file_name) || ($file_location != $old_file_location)) {
			if (!file_exists(STORE_FOLDER . "$file_location-$file_name")) {
            	rename(STORE_FOLDER . "$old_file_location-$old_file_name", STORE_FOLDER . "$file_location-$file_name");
        	} else {
				exit();
			}
		}
	if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
	    move_uploaded_file($_FILES['userfile']['tmp_name'], STORE_FOLDER."$file_location-$file_name");
        }
	else if(isset($file_content) && $file_content != ''){
	    $fp = fopen(STORE_FOLDER . "$file_location-$file_name", "wb");
	    fwrite($fp, $file_content);
	    fclose($fp);
	}
	$filesize = filesize(STORE_FOLDER."$file_location-$file_name");
	$mime_type = MIME_Magic::filenameToMIME(STORE_FOLDER."$file_location-$file_name");
	if(stristr($mime_type, $_SESSION['MGW']->settings['files_forbidden_mime'])){
	    $GLOBALS['log']->message(MGW_NOTICE, 'MIME type not allowed, discarding file', __LINE__, __FILE__);
	    unlink(STORE_FOLDER."$file_location-$file_name");
            deleteFile((int) $fileId);
	    return;
	}
    }
    else{
	$filesize = 0;
	$mime_type = '';
    }

    $sql="SELECT owner FROM mgw_files WHERE id=".(int)$fileId;
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $res = $res->FetchRow();

    if($res["owner"] == $_SESSION["MGW"]->userid){
	if($selectnewowner != 0)
	    $res["owner"] = $selectnewowner;

	$all_rights = getRightsFromForm($all_rights);

	$sql="UPDATE mgw_files SET project='".(int)$projectid."', category='".(int)$categoryid."', resides_in=".(int)$file_location.
	    ", name=".$conn->QMagic($file_name).", size=$filesize, mime_type='$mime_type', owner=".$res["owner"].
	    ", all_rights=$all_rights, modified=NOW(), task=".(int)$taskid.
	    " WHERE id=".(int)$fileId;
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	performGroupRights($fileId, $_POST['grouprights']);
    }
    else{
	$sql="UPDATE mgw_files SET project='".(int)$projectid."', category='".(int)$categoryid."', resides_in=".(int)$file_location.", name=".$conn->QMagic($file_name).", size=$filesize, mime_type='$mime_type', modified=NOW() where id=".(int)$fileId;
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }
    return;
}
    else
      $GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
}

// =================================================
//              Show File Details
// =================================================
function detailsPage(){
    global $smarty, $conn;

    $sql = getRightsQuery((int)$_GET['fileId']);
    if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if (($res['owner'] == $_SESSION['MGW']->userid) || checkForFileRight((int)$_GET['fileId'])){

    $smarty->assign("current_dir_name", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
    $smarty->assign("index_url", "index.php?".SID);

    //get the info of the file
    $smarty->assign("files", $res);

    if ($res["type"] == "d") {
	$sql = "SELECT COUNT(id) AS dirs FROM mgw_files WHERE type='d' AND resides_in=".(int) $_GET['fileId'];
	if(!$res = $conn->GetRow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$smarty->assign("numdirs", $res['dirs']);

	$sql = "SELECT COUNT(id) AS files FROM mgw_files WHERE type='f' AND resides_in=".(int) $_GET['fileId'];
	if(!$res = $conn->GetRow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$smarty->assign("numfiles", $res['files']);

	$sql = "SELECT SUM(size) AS dusage FROM mgw_files WHERE type='f' AND resides_in=".(int) $_GET['fileId'];
	if(!$res = $conn->GetRow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$smarty->assign("dusage", $res['dusage']);

	$smarty->assign("mode", "viewdir");
	$smarty->assign("file_details_header", Lang::getLanguageString("viewdir"));
        $smarty->assign("output", Lang::getLanguageString("emsg_fileisdirectory"));
    } else {
	$smarty->assign("mode", "viewfile");
	$smarty->assign("file_details_header", Lang::getLanguageString("viewfile"));

 	$file_name = STORE_FOLDER.$res["resides_in"]."-".$res["name"];
	$pretty = prettyPrint($file_name, (int) $_GET['fileId']);
	if ($pretty && ($pretty->getType() == 'text/html' || $pretty->getType() == 'text/plain')) {
	    if ($pretty->getType() == 'text/plain') {
		$smarty->assign("output", '<pre class="file_content">' . htmlspecialchars($pretty->render()) . '</pre>');
	    } else {
	        $smarty->assign("output", $pretty->render());
	    }
	}
	else{
	    $smarty->assign("output", Lang::getLanguageString("emsg_unsupportedfiletype"));
	}

    }

    $smarty->assign("suname", "post_action");
    $smarty->display("files_details.tpl"); 
    exit();
}
    else
      $GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
}

// =================================================
//              Email File
// =================================================
function emailFile(){
    global $smarty, $conn;

    $sql= getRightsQuery((int)$_GET['fileId']);
    if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    if (($res['owner'] == $_SESSION['MGW']->userid) || checkForFileRight((int)$_GET['fileId'])){

    $smarty->assign("current_dir_name", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
    $smarty->assign("index_url", "index.php?".SID);

    if(!copy(STORE_FOLDER.$res["resides_in"]."-".$res["name"],
	     CACHE_FOLDER.'../webmail2/sendmail/'.session_id()."######".$res["name"])){
	$GLOBALS['notify']->message(Lang::getLanguageString('emsg_mailcopyerror'), NOTIFY_SCREEN);
	return;
    }

    header('Location: ../webmail2/index.php?rightframe=sendmail.php?&'.SID);
    exit();
}
    else
      $GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
}

// =================================================
//	              Delete File
// =================================================
function doDelete(){
    global $smarty, $conn, $appconf;

    if(!isset($_POST['confirmation_no']) and !isset($_POST['confirmation_yes'])) {
      $sql= getRightsQuery((int)$_GET['fileId']);
      if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      if (($res['owner'] == $_SESSION['MGW']->userid) || checkForFileRight((int)$_GET['fileId'], DELE)){
        if ($res["type"] == "d") {
            $sql="SELECT COUNT(*) AS files FROM mgw_files WHERE resides_in = ".(int) $_GET['fileId'];
            if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $res2 = $res2->GetArray();

            if ((int)$res2[0]['files'] > 0) {
		$smarty->assign("menuid", "1");
		$smarty->assign("parms", $_SERVER["QUERY_STRING"]."&rDel=yes");
		$smarty->assign("reallydeleteitem", Lang::getLanguageString("emsg_directorynotempty"));
		$smarty->assign("deleteheader", Lang::getLanguageString("emsg_directorynotemptyh"));
		$smarty->assign("deletedetail1", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]."/" .$res["name"]);
		$smarty->assign("suclass", "submit");		
		$smarty->display($appconf["gentemplates"] ."/delete_item.tpl");
		exit;
            }
        }

	$smarty->assign("menuid", "1");
	$smarty->assign("parms", $_SERVER["QUERY_STRING"]);
	$smarty->assign("reallydeleteitem", Lang::getLanguageString("reallydel"));
	$smarty->assign("deleteheader", Lang::getLanguageString("deleteh"));
	$smarty->assign("deletedetail1", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]."/" .$res["name"]);
	$smarty->assign("suclass", "submit");		
	$smarty->display($appconf["gentemplates"] ."/delete_item.tpl");
	exit();
    }
      else
	$GLOBALS['notify']->message(Lang::getLanguageString('permerrormsg'), NOTIFY_SCREEN);
    }
    if (isset($_POST['confirmation_yes'])) {
      $sql= getRightsQuery((int)$_GET['fileId']);
      if(($res = $conn->GetRow($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      if (($res['owner'] == $_SESSION['MGW']->userid) || checkForFileRight((int)$_GET['fileId'], DELE)){
        if ($_GET['rDel'] == "yes") {
            recursiveDeleteDirectory($_GET['fileId']);
        } else {
            deleteFile($_GET['fileId']);
        }
    }
}
}

// =================================================
//	              List Files
// =================================================
function listFiles() {
    global $smarty, $conn, $appconf;
    include_once('./inc/mime/Part.php');
    include_once('./inc/mime/Magic.php');
    include_once('./inc/mime/Viewer.php');
    include_once('./inc/category.class.php');
    include(INCLUDEPATH . "mSelectBox.class.php");

    if(isset($_POST["files"]["post_action"]) && $_POST["files"]["post_action"] == Lang::getLanguageString("download")) {
	doDownload();
    }
    checkSessionDir();
    
    if (isset($_GET['chgDirId'])) {
	if ($_GET['chgDirId'] == "up") {
	    $sql="SELECT resides_in, name FROM mgw_files WHERE id=".(int) $_SESSION["MGW"]->settings["files"]["curr_dir_id"];
            if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    $res = $res->FetchRow();

	    if ($res["resides_in"] == "")
                $res["resides_in"] = 0;

	    $_SESSION["MGW"]->settings["files"]["curr_dir_id"] = $res["resides_in"];
            $tmp_dir_name = explode("/", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
            array_pop($tmp_dir_name);
            $_SESSION["MGW"]->settings["files"]["curr_dir_name"] = implode("/", $tmp_dir_name);	
	} else {
	    if ($_GET['chgDirId'] != $_SESSION["MGW"]->settings["files"]["curr_dir_id"]) {
		$sql="SELECT id, name FROM mgw_files WHERE id=".(int) $_GET['chgDirId'];
                if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		$res = $res->FetchRow();				
		$_SESSION["MGW"]->settings["files"]["curr_dir_id"] = $res["id"];
                $tmp_dir_name = explode("/", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
                array_push($tmp_dir_name, $res["name"]);
                $_SESSION["MGW"]->settings["files"]["curr_dir_name"] = implode("/", $tmp_dir_name);
	    }				
	}
    }
	
    if (isset($_POST['cat']) and $_POST['cat']!="0") $st = $_POST['cat']."%";
    if (isset($_POST['pro']) and $_POST['pro']!="0") $st .= $_POST['pro']."%";
    if (isset($_POST['searchterm'])){
	$st.= $_POST['searchterm'];
	$_POST['searchterm'] = $st;
    }
	
    if ((isset($_POST['search'])) and (isset($_POST['searchterm']))) {
	$smarty->assign("searchterm",$_POST['searchterm']);
	$sql = getRightsQuery3();
	// TODO: a search!
    } else {
	//$sql = getRightsQuery2();
    }
    
    // Security check. Might not be able to access this dir.
    // this is ugly at the moment.
    if (!checkForFileRight($_SESSION["MGW"]->settings["files"]["curr_dir_id"], READ)) {
	if ($_SESSION["MGW"]->settings["files"]["curr_dir_id"] != 0) {
	    $_GET["chgDirId"] = 0;
	    return listFiles();
	} else {
	    exit("Bad permissions");
	}
    }
	
    $icons = getIconStrings();
		    
    $smarty->assign("current_dir_name", $_SESSION["MGW"]->settings["files"]["curr_dir_name"]);
    $smarty->assign("chgdir_up", "<a href=\"index.php?chgDirId=up&".SID."\">../</a>");
    if (queryRights2_bool("root_modules_files_files_write"))
	$smarty->assign("chgdir_up_actions", "<a href=\"index.php?action=newform&".SID."\">".$icons['new']."</a>");
    else
	$smarty->assign("chgdir_up_actions", "&nbsp;");

    $rawinfo = getFilesInDir();
    $count = 0;
    $numdirs = 0;
    $numfiles = 0;
    $dusage = 0;
    foreach ($rawinfo as $idx => $row) {
	$td[$count]['name'] = $row['name'];
	$td[$count]['size'] = $row['size'];
	$td[$count]['owner'] = $row['owner'];
	$td[$count]['owner_name'] = getUsername($row['owner']);
	$td[$count]['rights'] = "";
	$td[$count]['modified'] = $conn->UnixTimeStamp($row['modified']);
	$td[$count]['created'] = $conn->UnixTimeStamp($row['created']);
	if (isset($row['category']))
	    $td[$count]['category'] = Category::catName($row['category']);
	$td[$count]['project'] = $conn->GetOne('SELECT title FROM mgw_projects WHERE project_id='.(int)$row['project']);

	$td[$count]['actions'] = '';
 		
	$td[$count]['actions'] .= "<a href=\"index.php?action=details&amp;fileId=". $row["id"] ."&".SID."\">".$icons['details']."</a>&nbsp;&nbsp;";
         
	if ($row['type'] == 'f') {
	    $td[$count]['name'] = "<a href=\"serve.php?id=". $row["id"] . "&amp;dl=1&amp;".SID."\" target=\"_blank\">". $row["name"] ."</a>&nbsp;&nbsp;";
	    $td[$count]['actions'] .= "<a href=\"index.php?action=copyform&amp;fileId=". $row["id"] ."&".SID."\">".Lang::getLanguageString('copy')."</a>&nbsp;&nbsp;";
	}
 		
	if (hasRight($row['rights'], WRIT)) {
	    $td[$count]['actions'] .= "<a href=\"index.php?action=editform&amp;fileId=". $row["id"] . "&".SID."\">".$icons['edit']."</a>&nbsp;&nbsp;";
	}
	if (hasRight($row['rights'], DELE)) {
	    $td[$count]['actions'] .= "<a href=\"index.php?action=delete&amp;fileId=". $row["id"] . "&".SID."\">".$icons['delete']."</a>";
	}
	
	if ($row['type'] == 'd')
	    $td[$count]['name'] = "<a href=\"index.php?chgDirId=". $row["id"] ."&".SID."\">". htmlentities($row["name"]) ."/</a>";
	if ($row['type'] == 'd')
	    $td[$count]['icon'] = '<img src="'.$appconf['imgpath'].'/folder.png" />';
 	else
	    $td[$count]['icon'] = '<img src="'.$appconf['imgpath'].'/'.MIME_Viewer::getIcon(MIME_Magic::filenameToMIME($row['name'])).'" />';
 	
	if ($row['type'] == 'd') {
	    $numdirs++; 
	    $sql = "SELECT SUM(size) FROM mgw_files WHERE type='f' AND resides_in=".(int)$row['id'];
	    if(($size = $conn->GetOne($sql)) === false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    $row['size'] = $size;
	    $dusage += $size;
	}
	else {
	    $numfiles++;
	    $dusage += (int) $row['size'];
 	}
 	
     	$count++;    	
    }
    
    $smarty->assign("td", $td);
    
    $smarty->assign("numdirs", $numdirs);
    $smarty->assign("numfiles", $numfiles);
    $smarty->assign("dusage", $dusage);

    $sql = "SELECT COUNT(id) AS dirs FROM mgw_files WHERE type='d'";
    if(!$res = $conn->GetRow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $smarty->assign("tnumdirs", $res['dirs']);

    $sql = "SELECT COUNT(id) AS files FROM mgw_files WHERE type='f'";
    if(!$res = $conn->GetRow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $smarty->assign("tnumfiles", $res['files']);

    $sql = "SELECT SUM(size) AS dusage FROM mgw_files WHERE type='f'";
    if(!$res = $conn->GetRow($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $smarty->assign("tdusage", $res['dusage']);
	
    if(isModuleInstalled('projects')){
	//create a select box for project search
	$sb6 = new mSelectBox("pro");
	$sb6->setContentType("sql");
	$sb6->setSQLvalue("project_id");
	$sb6->setSQLcontent("title");
	$sb6->addContent("select project_id, title from mgw_projects order by title");
	$sb6->addOption("0","", "pre");
	$smarty->assign("projectssb", $sb6->draw());
    }
    
    //create a select box for category search
    $sb7 = new mSelectBox("cat");
    $sb7->setContentType("sql");
    $sb7->setSQLvalue("id");
    $sb7->setSQLcontent("name");
    $sb7->addContent("select id, name from mgw_files_categories order by name");
    $sb7->addOption("0","", "pre");
    $smarty->assign("categoriessb", $sb7->draw());
    $smarty->assign("projectsupport", isModuleInstalled('projects'));

    $smarty->display("files_list.tpl");     
    exit();
}

?>
