<?php
defined('WikyBlog') or die("Not an entry point...");

//
//		functions that are not the same between FileSystemFTP.php and FileSystem.php
//	
//		This set of functions should only be used when the installation is on a safe_mode enabled system
//		and CHMODing directories is not enough
//
//

	//translate absolute paths to ftp paths
	//	absolute paths will always be longer
	function ftpTranslateLocation(&$location){
		global $wbFTP,$rootDir;
		
		$len = strlen($rootDir);
		$temp = substr($location,$len);
		return $wbFTP['root'].$temp;
	}
	
	function ftpConnect(){
		global $wbFTP;
		static $conn_id = false;
		
		if( $conn_id ){
			return $conn_id;
		}
		
		
		$conn_id = @ftp_connect($wbFTP['server'],21,6);
		if( !$conn_id ){
			trigger_error('ftp_connect() failed for server : '.$wbFTP['server']);
			return false;
		}
		$login_result = @ftp_login($conn_id,$wbFTP['user'],$wbFTP['pass'] );
		if( !$login_result ){
			trigger_error('ftp_login() failed for server : '.$wbFTP['server'].' and user: '.$wbFTP['user']);
			return false;
		}
		register_shutdown_function('ftpClose',$conn_id);
		return $conn_id;
	}
	
	function ftpClose($connection){
		if( $connection ){
			@ftp_quit($connection);
		}
	}
	
	//Attemps to save a file..
	//	if the file does not exist it attempts to create it
	//	
	
	function saveFile(&$fileLocation,&$contents){
		global $wbFTP;
		
		//using call to makeDir() instead of makeFile()
		$dir = dirname($fileLocation);
		if( !makeDir($dir) ){
			return false;
		}
		
		$ftpLocation = ftpTranslateLocation($fileLocation);
		
		
		if(!($handle = tmpfile())){
			trigger_error('Couldn\'t create temporary file.');
			return false;
		}
		
		if( fwrite($handle,$contents) === false ){
			trigger_error('Couldn\'t write to temporary file.');
			return false;
		}
		rewind($handle);
		
		$conn_id = ftpConnect();
		
		if( !ftp_fput($conn_id,$ftpLocation,$handle, FTP_ASCII)){
			trigger_error('ftp_fput failed.');
			return false;
		}
		fclose($handle);
		return true;
	}
	
	
	//Attempts to create a directory
	//accepts paths that include filenames, it will just remove the filename
	function makeDir($relPath){
		global $rootDir,$wbFTP;
		
		
		if( @is_dir($relPath)){
			//message('FTP: already exists');
			return true;
		}
		
		//Must be a subdir of $rootDir
		if( wbStrpos($relPath,$rootDir) === false){
			trigger_error('Tried to create an illegal directory for: '.$fileLocation);
			return false;
		}
		
		$relPath = wbStr_replace($rootDir.'/','',$relPath);
		$newParts = explode('/',$relPath);
		
		$part = '/'.array_shift($newParts);
		$newDir = $rootDir.$part;
		$newDirFTP =  $wbFTP['root'].$part;
		
		//The immediate subdir of $rootDir must already exist
		if( !@is_dir($newDir) ){
			trigger_error('The subdirectory to the rootdir must already exist: '.$fileLocation);
			return false;
		}
		$conn_id = ftpConnect();
		
		foreach($newParts as $piece){
			$newDir.='/'.$piece;
			$newDirFTP.= '/'.$piece;
			
			//message($newDir);
			if( @is_dir($newDir) ){
				continue;
			}
			
			if( ftp_mkdir($conn_id,$newDirFTP) ){
				continue;
			}
			
			trigger_error('FTP: Could not create directory: '.$newDir.' with ftp path: '.$newDirFTP);
			return false;
		}
		return true;
	}
	
	
	function renameFile($from,$to){
		$toDir = dirname($to);
		
		if( !makeDir($toDir) ){
			return false;
		}
		
		$fromFTP = ftpTranslateLocation($from);
		$toFTP = ftpTranslateLocation($to);
		$conn_id = ftpConnect();
		
		if( !ftp_rename($conn_id,$fromFTP, $toFTP) ){
			trigger_error('FTP: Couldn\'t rename '.$from. ' to '. $to);
			return false;
		}
		return true;
	}

	function wbMove_uploaded_file($from, $to){
		$conn_id = ftpConnect();
		$toFTP = ftpTranslateLocation($to);
		
		if( ftp_put($conn_id, $toFTP, $from, FTP_BINARY ) ){
			return true;
		}
		return false;
	}
	
	function wbUnlink($path){
		//use is_file instead of file_exists in case of safe mode
		if( !is_file($path) ){
			return true;
		}
		$conn_id = ftpConnect();
		$pathFTP = ftpTranslateLocation($path);
		return ftp_delete($conn_id,$pathFTP);
	}
	function wbRmdir($path){
		$conn_id = ftpConnect();
		$pathFTP = ftpTranslateLocation($path);
		return  ftp_rmdir($conn_id,$pathFTP);
	}
	function wbChmod($file,$mode){
		$conn_id = ftpConnect();
		$pathFTP = ftpTranslateLocation($file);
		
		if( !function_exists('ftp_chmod') ){
			return ftp_site($conn_id, sprintf('CHMOD %o %s', $mode, $pathFTP));
		}else{
			//php5 only!
			return ftp_chmod($conn_id, $mode, $pathFTP ); //false on failure, new mode on success
		}
	}
	
	function wbSaveCompressed($destination,&$contents,$compressType){
		
		if( $compressType == '.gz'){
			$contents = gzencode($contents);
		}elseif( $compressType == '.bz' ){
			$contents = bzcompress($contents);
		}else{
			return false;
		}
			
		if( !saveFile($destination,$contents) ){
		    return false;
		}
		return true;		
	}
	
//
//		functions that are not the same between FileSystemFTP.php and FileSystem.php
//	
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
//
//		These funcitons are the same for FileSystemFTP.php and FileSystem.php
//


	// check to make sure a supplied path is a subdirectory of $rootdir
	function checkPath($dir,$subDir='',$trigger=true){
		global $rootDir;
		$check = $rootDir.'/'.$subDir;
		
		//try to get rid of ../
		$dir = wbStr_replace('\\','/',$dir);
		$dir = wbStr_replace('../','/',$dir);
		$dir = wbStr_replace('./','/',$dir);
		
		
		//check for more ./
		if( wbStrpos($dir,'./') !== false ){
			if($trigger){
				trigger_error('Illegal path supplied to checkPath() (1): '.$dir);
			}
			return false;
		}
		
		//should be in $check
		if( wbStrpos($dir,$check) === false){
			if($trigger){
				trigger_error('Illegal path supplied to checkPath() (2): '.$dir);
			}
			return false;
		}
		
		return true;
	}



	//
	//		saveAsPHP
	//	
	
	
	function saveAsPHP(&$location,$varName,&$mixed,$global=false){
		
		$text = '<'.'?'."php\n";
		$text .= "//\n";
		$text .= "//\t\tWikyBlog Generated File\n";
		$text .= "//\t\t*****************************************************\n";
		$text .= "//\t\tThis file contains data used by the wikyblog software\n";
		$text .= "//\n\n";
		$text .= 'defined(\'WikyBlog\') or die(\'Not an entry point...\');';
		$text .= "\n\n";
		
		if( $global ){
			$text .= 'global $'.$varName.";\n";
		}
		$text .= '$'.$varName." = \n";
		$text .= var_export($mixed,true);
		$text .= ';';
	
		return saveFile($location,$text);
	}
	
