<?php


class FirstInstallation {
 
	private static $instance;
		
 	static public function getInstance(){
 		if(self::$instance==null) self::$instance = new FirstInstallation();
 		return self::$instance;
 	}
 	 
	public function __construct(){

	}
	
	
	function canAccessToInstaller($d){
	 	
	 	
	 	$retObj = (object) array();
	 	$retObj->success = true;
	 	
	 	$retObj->defaultLanguageData = Languages::getInstance()->getLanguage((object) array("language"=>"__default"), false, true);
	 	if(!empty($d->language)){
	 		$retObj->languageData = Languages::getInstance()->getLanguage((object) array("language"=>$d->language), false);
	 	}
		
		$retObj->selfDirURL = Util::selfDirURL();
	 		
	 	
	 	Response::sendOKResponse($retObj);
	 	
	}
	
	function saveConfiguration($d){
	
		$configFileContent = implode('', file('config.template.php'));
		
		$ud = new UD();
		
		foreach($d as $key=>$value){
		 	if($key!="chmodFile" && $key!="chmodDir" && $key!="http_path" && $key!="http_public_path")
		 		$value = UD::getRealPath($value);
			$configFileContent = str_replace(strtoupper("{".$key."}"), 	$value, $configFileContent);
		}
		
		$retObj = (object) array();
		$retObj ->success = $this->fileWrite("config.php", octdec("0".$d->chmodFile), $configFileContent);
	 		
	 		
		Response::sendOKResponse($retObj);
	}
	
	function copyInstallationFiles(){
	

		$ud = new UD();
			
		// Master account group
	 	$p = Config::get("private_system_accountsGroups_path")."/Master.txt";
	 	Util::copyFile("resources/templates/Master.txt", $p);
	 	
		// applicationsInfo
	 	$p = Config::get("private_system_path")."/modules/applicationsInfo.xml";
	 	Util::copyFile("resources/templates/applicationsInfo.xml", $p);
	 	
	 	// fonts
	 	$p = Config::get("private_system_path")."/fonts/fonts.txt";
	 	Util::copyFile("resources/fonts/fonts.txt", $p);
	 	$FaF = $ud->getFoldersAndFiles("resources/fonts/swf");
	 	for($i=0; $i<count($FaF); $i++){
	 	 	$p = Config::get("private_system_path")."/fonts/swf/".$FaF[$i]["name"];
	 		Util::copyFile("resources/fonts/swf/".$FaF[$i]["name"], $p);
		}
	 		
		Response::sendOKResponse((object) array("success"=>true));
		
	}
	
	function createMasterAccount($d){
	 
		User::getInstance()->registerUser($d);

	}

	function sendEmail($d){
		$retObj = (object) array();
		$retObj->success = mail($d->email, "FWindows installation", "Test email message.");
		Response::sendOKResponse($retObj);
	}
	
	function checkUploadFile(){
		$retObj = (object) array();
		$retObj->success = is_file("testUploadFile.tmp");
		if($retObj->success){
			unlink("testUploadFile.tmp");
		}
		Response::sendOKResponse($retObj);
	}
	
	function uploadFile(){
		move_uploaded_file($_FILES['Filedata']['tmp_name'], "testUploadFile.tmp");
	}

	function getLicense(){
	
		$retObj = (object) array();
		$retObj->license = Util::readFile('license.txt');
		
		Response::sendOKResponse($retObj);
		
	}
	
	function createAndCheckPaths($d){
		
		$ud = new UD();
		$retObj = (object) array();
		$chmod_dir = octdec("0".$d->chmodDir);
		$retObj->publicPathSuccess = $this->createDirectory(UD::getRealpath($d->publicPath), $chmod_dir);
		$retObj->privatePathSuccess = $this->createDirectory(UD::getRealPath($d->privatePath), $chmod_dir);
		if($retObj->privatePathSuccess==true){
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/applications_installations"), $chmod_dir);
			$this->createDirectory(UD::getRealPath($d->privatePath."/users"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/accounts"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/accountsGroups"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/config"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/config/groups"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/config/system"), $chmod_dir);
			$this->createDirectory(UD::getRealPath($d->privatePath."/system/config/users"), $chmod_dir);
			$this->createDirectory(UD::getRealPath($d->privatePath."/system/databaseInfo"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/fonts"), $chmod_dir);
		  	$this->createDirectory(UD::getRealPath($d->privatePath."/system/fonts/swf"), $chmod_dir);
		  	$this->createDirectory(UD::getRealPath($d->privatePath."/system/indexes"), $chmod_dir);
		  	$this->createDirectory(UD::getRealPath($d->privatePath."/system/keys"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/logs"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/logs/___index"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/logs/___index/date"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/logs/___index/user"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/logs/___index/application"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/logs/___index/method"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/modules"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/privilegies"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/sessions"), $chmod_dir);
		 	$this->createDirectory(UD::getRealPath($d->privatePath."/system/tmp"), $chmod_dir);
		 
			$pathsObj =  (object) array();
			$pathsObj->private_path = $d->privatePath;
			$pathsObj->public_path = $d->publicPath;
			$pathsObj->server_path = $d->serverPath;
			
				
			$pathsObj->http_path = $d->httpPath;
			$pathsObj->http_public_path = $d->httpPublicPath;
			
			$retObj->pathsObj = $pathsObj;
			
		}
		
		$retObj->serverPathSuccess = $this->isDirReadable(UD::getRealPath($d->serverPath));
	
		// todo: find solution for next two
		$retObj->httpPathSuccess = true;
		$retObj->httpPublicPathSuccess = true;

		Response::sendOKResponse($retObj);
		
	}

	function startSession($d){
		
		session_id(md5(microtime().$userInfo->password));
		$errorCount1 = count(Error::getErrorArray());
 		session_start();
 		$errorCount2 = count(Error::getErrorArray());
 		User::setTestSessionData("TEST");
 		$retObj = (object) array();
 		$retObj->session = session_id();
 		$retObj->success = $errorCount1==$errorCount2;
 		
 		Response::sendOKResponse($retObj);
	}
	function restoreSession($d){
	 
		session_id($d->session);
		session_start();
		$retObj = (object) array();
		$retObj->success = (User::getTestSessionData()=="TEST");
		$retObj->restoreSuccess = $retObj->success ;
		Response::sendOKResponse($retObj);
		
	}
	function checkFileManagament($d){
	 	
	 /*	$d->chmodDir="755";
	 	$d->chmodFile=1;*/
	 	if($d->chmodFile){
	 		$retObj = $this->checkFileManagament2(octdec("0"+$d->chmodFile), octdec("0"+$d->chmodDir));
	 		$retObj->chmodFile = $d->chmodFile;
	 		$retObj->chmodDir = $d->chmodDir;
	 	}else{
			$successArr1 = $this->checkFileManagament2(octdec("0644"), octdec("0755"));
			$retObj = $successArr1; 
			$retObj->chmodFile = "644";
	 		$retObj->chmodDir = "755";
			if($successArr1->success==false){
				$successArr2 = $this->checkFileManagament2(octdec("0666"), octdec("0777"));
				if($successArr2->success==true){
					$retObj = $successArr2; 
					$retObj->chmodFile = "666";
	 				$retObj->chmodDir = "777";
				}
			}
		}
		$retObj->safe_mode = (ini_get('safe_mode') ? true : false);
		$retObj->os = substr( php_uname(), 0, 7 ) == "Windows" ? "win" : "nix" ;
	
		Response::sendOKResponse($retObj);
		
	}
	
	function checkFileManagament2($chmod_file, $chmod_dir){
		
		$checkObj = (object) Array(); 
		$checkObj->success = true;
	
		// ======================================================		
		// directory creation
		$checkObj->createDir = mkdir("fw_testDir", $chmod_dir);

		// ======================================================		
		// file creation
		$checkObj->createFile = $this->fileWrite("fw_testDir/testFile.php", $chmod_file, '<?php $executing = true; ?>');

		// ======================================================
		// file reading
		$checkObj->readingFile = (@file("fw_testDir/testFile.php") !== false);
		
		// ======================================================
		// file executing
		include("fw_testDir/testFile.php");
		$checkObj->executingFile = ($executing == true);
		
		// ======================================================
		// file removing
		$checkObj->removingFile = unlink("fw_testDir/testFile.php");

		
		// ======================================================
		// directory removing
		$checkObj->removingDir =  rmdir("fw_testDir");

		foreach($checkObj as $value){
			if($value==false) $checkObj->success = false;
		}

		return $checkObj;
		
		
	}
		
	function fileWrite($filename, $chmod_file, $content){
		
		if (!$handle = fopen($filename, 'w')) { 
	        return false; 
		} 
	
		if (!fwrite($handle, $content)) { 
			fclose($handle); 
			return false; 
		} 
		 
		fclose($handle); 
		
		@chmod($filename, $chmod_file);
		
		return true;
			                    
	}
		
			
	function createDirectory($dirPath, $chmod){
			
		if(is_dir($dirPath)){
			return true; 
		} 
		
		if(mkdir($dirPath)===false){
			return false;
		}
		
		chmod($dirPath, $chmod);
		
		return true;
		
	}
	
	function isDirReadable($dirPath){	
		if (!is_dir($dirPath)) return false;
		
		if ($dh = opendir($dirPath)) {
			closedir($dh);
			return true;
		}
		return false;
	}
	 	

	/*function getModules($d){

	 	
	 	$applXmlSrt = Util::readFile("resources/modules/applications.xml");
	 	if($applXmlSrt==false){
	 		Response::sendResponse(false, null);
	 	}
	 	
	 	$applArray = WddxSerializer::deserialize($applXmlSrt);

		
 		Response::sendOKResponse($applArray);
 		
	}*/
	 	

}