<?php
if ( !defined('IN_MFA') )
	die("Hacking attempt");

//*****************
//*USER-FUNKTIONEN*
//*****************
function getusers()
{
	//öffnet das UServerzeichnis und gibt eine Liste aller registrierten Benutzer zurück
	//vll wär es günstig mal auf SQL umzusteigen.
	$dh = @opendir( ROOT_DIR."/".SCRIPT_PATH."/work/data/" );
	$users = array();
	while ( gettype($file = readdir( $dh )) != "boolean")
	{
		if(($file != ".") && ($file != "..") && strstr($file,"user_") && strstr($file,".php"))
		{
			$luser = str_replace("user_","",$file);
			$luser = str_replace(".php","",$luser);
			$luser = new users($luser);
			$users[$luser->user_id] = $luser->user_name;
		}
	}	
	return $users;
}

function getuser($username)
{
	//gibt informationen über einen speziellen user als array zurück
	$user_file = new file(SCRIPT_PATH."/work/data/user_".strtolower($username).".php");
	
	if(!file_exists(ROOT_DIR."/".$user_file->file_path)) return false;
	$fcontent = $user_file->getContent();
	if(gettype($fcontent) == "boolean")
		return false;
	
	$allusers = explode(";", $fcontent);  //erste Unterteilung in Datensätze

	$string_parts = explode(";", $fcontent);  //erste Unterteilung in Datensätze
	foreach($string_parts  as $user)
	{
		if(strstr($user, ","))
			$userinformation = explode(",", $user); //Unterteilung in Attributwerte
	}
	Return $userinformation;
}

function write_userdata($user)
{
		//die schönste Funktion überhaupt.
		//Übergeben, wird eine Array, die die Daten eines Users enthält. Die Array wird dann in eine
		//Userdatei geschrieben
		if(!file_exists(ROOT_DIR."/".SCRIPT_PATH."/work/data/user_".strtolower($user[1]).".php"))
		{
			//temporäre Datei erstellen
			$tmpfile = create_tmpfile();
			$tmpfile = new file(SCRIPT_PATH."/".$tmpfile);
			//die an den richtigen Art verschieben
			$tmpfile->move_to(SCRIPT_PATH."/work/data/user_".strtolower($user[1]).".php");
			$tmpfile->delete();
		}
		
		$ufile = new file(SCRIPT_PATH."/work/data/user_".strtolower($user[1]).".php");
		
		if(!$ufile->open("w"))
			return false;
		
		fwrite($ufile->file_resource, "");
		fputs($ufile->file_resource, "<?php/*;");
		
		$user_data = implode(",",$user);
		//$user[0].",".$user[1].",".$user[2].",".$user[3].",".$user[4].",".$user[5].",".$user[6].",".$user[7].",".$user[8].";";
		fputs($ufile->file_resource, $user_data);

		fputs($ufile->file_resource, ";*/?");
		fputs($ufile->file_resource, ">");
		$ufile->close();
		return true;
}

//****************************************
//*FUNKTIONEN FÜR DAS SPEREEN VON DATEIEN*
//****************************************
function is_locked($file_path) //Gibt entweder false zurück oder den User, der die Datei bearbeitet
{
	if(file_exists(ROOT_DIR."/".SCRIPT_PATH."/work/data/lock_".md5($file_path)))
	{
		$lock_file = new file(SCRIPT_PATH."/work/data/lock_".md5($file_path));
 		$fcontent = $lock_file->getContent();
 		$fcontent = explode("##;##",$fcontent);
		return $fcontent[1];
	}
	else
		return false;
}
//schreibt eine Lock_Datei
function write_lock_file($file_path,$user_id)
{
	global $ftp_conn_id,$user;
	$tmpfile = create_tmpfile();
	$tmpfile = new file(SCRIPT_PATH."/".$tmpfile);
	if(!$tmpfile->open("w"))
			return false;
		
	fwrite($tmpfile->file_resource, "");
	fputs($tmpfile->file_resource, $file_path."##;##".$user_id);
	
	$tmpfile->close();
	if(FTP_USED == 1)
  	ftp_put($ftp_conn_id , FTP_ROOT."/".SCRIPT_PATH."/work/data/lock_".md5($file_path), ROOT_DIR."/".$tmpfile->file_path , FTP_BINARY);
  else
  	copy( ROOT_DIR."/".$tmpfile->file_path ,ROOT_DIR."/".SCRIPT_PATH."/work/data/lock_".md5($file_path));

	$tmpfile->delete();
	
	return true;
}

//wenn z.B: Datei umbennant wird
function update_lock_file($old_path,$new_path)
{
	$is_locked = is_locked($old_path);
	if(gettype($is_locked) != "boolean")
	{
		unlock_file($old_path);
		return write_lock_file($new_path,$user->user_id);
	}
}
function is_locked_for_me($file_path)
{
	global $user;
	$is_locked_by = is_locked($file_path);
	if(gettype($is_locked_by) == "boolean") 
		return false;
	else
		return ($is_locked_by == $user->user_id)?false:true;
}
//sperrt Datei
function lock_file($file_path)
{	
	global $ftp_conn_id,$user;	
	return write_lock_file($file_path,$user->user_id);
}
function unlock_file($file_path)
{
	//demarkiert eine Datei, indem einfach die Sperrdatei entfernt wird.
	if(file_exists(ROOT_DIR."/".SCRIPT_PATH."/work/data/lock_".md5($file_path)))
	{
		//mfa-Core macht es möglich
		$lock_file = new file(SCRIPT_PATH."/work/data/lock_".md5($file_path));
 		$lock_file->delete();
 		return true;
	}
	return false;
}

//*****************
//*Logbuch				*
//*****************
function write_in_log($logstr)
{
	//schreibt was in das globale Logbuch
	global $user;
	if(!file_exists(ROOT_DIR."/".SCRIPT_PATH."/work/log"))
		touch(ROOT_DIR."/".SCRIPT_PATH."/work/log");
	
	$log = new file(SCRIPT_PATH."/work/log");
	$fcontent = $log->getContent();
	if(!$log->open("w"))
		return false;
	$time_of_action = getdate();
	$time_of_action = $time_of_action['mday'].".".$time_of_action['mon'].".".$time_of_action['year']." ".$time_of_action['hours'].":".$time_of_action['minutes']." Uhr";
	fwrite($log->file_resource, $time_of_action." (by ".$user->user_name."): ".$logstr."\n");
	fputs($log->file_resource, $fcontent);
	$log->close();
}

//******************
//*DATEI-FUNKTIONEN*
//******************
function find_file_name($file_path)
{
	return basename(ROOT_DIR."/".$file_path);
}

//findet das Parent Directoy eines Verzeichnisses(z.b /doc/html --> /doc)
function find_parent_dir($verz)
{
	//findet übergeordnete Verzeichnisebene
	if(substr($verz, strlen($verz)-1) == "/") //wenn noch ein Schrägstrich hinten dran ist
  	$verz = substr($verz, 0,strlen($verz) - 2);
	
	$verz_length = strlen($verz);
	for($I = $verz_length-1; $I >= 0; $I--)
		if($verz[$I] == "/" || $I == 0)
			return substr($verz,0,$I);
}

//für phpversion() < 5
if (!function_exists('ftp_chmod')) {
   function ftp_chmod($ftp_stream, $mode, $filename)
   {
       return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
   }
}

//Unterverzeichnise lesen. Nun auch rekursiv.
function get_subdirectories($path)
{
	$result = array();

  $fp = opendir(ROOT_DIR."/".$path); 

  while (gettype($file = readdir($fp)) != "boolean") 
  { 
    $name = $path."/".$file;
		if (is_dir(ROOT_DIR."/".$name) && $file != "." && $file != "..") 
    {              
      $result[] = $name;
			$ar = get_subdirectories($name);
      foreach ($ar as $value)
        $result[] = $value;        
    } 
  }     
  closedir($fp);
  return $result;
}
function create_tmpfile()
{
	//erstellt eine temporäre Datei in work/temp/
	global $user;
  $tmpfile1 = "work/temp/".$user->user_name.md5(microtime());
	touch($tmpfile1);
	$tmpfile2 = "work/temp/".$user->user_name.$user->user_id.md5(microtime());
	$tmpfile = new file(SCRIPT_PATH."/".$tmpfile1);
	$tmpfile->move_to(SCRIPT_PATH."/".$tmpfile2);
	unlink($tmpfile1);
	return $tmpfile2;
}

//*****************
//*OTHER					*
//*****************
function validateObject($object)
{
	//validiert die Variable $_GET['object'];allgemein per $_GET übergebene Dateipfade
	global $user,$lang;
	//no double points in the url
	if(strstr($object, ".."))
   return "Do not use '../' in the URL";
  //double slashes in the url!
  $object = preg_replace("|(/{2,})|", "/", $object); 
	//do not open mfa-files
	if(stristr($object,SCRIPT_PATH))
		return $lang['not_this_dir'];
	if(!is_dir(ROOT_DIR."/".$object))
	{
		$display = new file_info($user->user_root_dir.$_GET['object']);
		if($display->isScript() && !$user->has_right("scripting"))
			return $lang['norights'];
	}
	return true;
}
function message_die($title,$message,$type = "Message",$redirect = 2,$redirect_to = "")
{
	//gibt Fehlermeldung inklusive Umleitung aus
	global $template,$ftp_conn_id, $verzname;
	
	$redirect_to = "index.php?dir=".$verzname.(($redirect_to != "")? "&amp;mode=".$redirect_to : "");
	
	$layoutargs['host_name'] = HOST_NAME;
	$layoutargs['redirect'] = ($redirect > 0)?"<meta http-equiv='refresh' content='".$redirect.";url=".$redirect_to."'>":"";
	$layoutargs['msg_type'] = $type;
	$layoutargs['message'] = 
	 "<div class='box'>
			<p style='text-align:center;width:100%;font-size:16pt'>".$title."</p>
			<div class='hr' width='100%'></div>
			<p align='center'>".$message."</p>
		</div>";
	echo $template->layoutparser("msgbox",$layoutargs);
	
	if(FTP_USED == 1)
		ftp_quit($ftp_conn_id);
	exit;
}

function chconfig($host_name,$ftp_used,$log_used,$read_only)
{
	//Ändert die Konfiguration
	//Wenn letzter Buchstabe = "/", dann abtrennen
	if(substr($host_name, -1) == "/") 
		$host_name = substr($host_name, 0,strlen($host_name) - 1);
 		
	//wenn LOGBUCH deaktiviert wird
	if($log_used < LOG_USED)
		write_in_log("log deactivated!");
	
	$config_file = new file(SCRIPT_PATH."/work/data/constants.php");
	if(!$config_file->open("w"))
		return false;

	fwrite($config_file->file_resource, "");
	fputs($config_file->file_resource, "<?php\n");
	fputs($config_file->file_resource, "define(\"HOST_NAME\", \"".$host_name."\");\n");
	fputs($config_file->file_resource, "define(\"ROOT_DIR\", \"".ROOT_DIR."\");\n");				 
	fputs($config_file->file_resource, "define(\"SCRIPT_PATH\", \"".SCRIPT_PATH."\");\n");				
	fputs($config_file->file_resource, "define(\"FTP_USED\", ".$ftp_used.");\n");
	fputs($config_file->file_resource, "define(\"FTP_ROOT\", \"".FTP_ROOT."\");\n");
	fputs($config_file->file_resource, "define(\"LOG_USED\", ".$log_used.");\n");
	fputs($config_file->file_resource, "define(\"READ_ONLY\", \"".$read_only."\");\n");
	fputs($config_file->file_resource, "?"); fputs($config_file->file_resource, ">");

	$config_file->close();
	return true;
}
?>