### cls_ftp.php ###
<?php
// --------------------------------------------------------------------------------------------------
// Class name:  clsFTP
// Dependency:	constructException.php
//				ftpException.php
// State:		protoype 
// --------------------------------------------------------------------------------------------------

class clsFtp{
	// Properties ########################################
	private $m_FtpUserName;
	private $m_FtpUserPass;
	private $m_FtpHost;
	public	$m_FtpStream;
	private $m_FtpPort;
	private $m_resumeDownload = false;
	private $m_downloadDir; // Location to download the file temp...
	private $m_currentDir;
	// Methods #########################################
	public function __construct($p_FtpHost, $p_FtpUserName, $p_FtpUserPass, $p_FtpPort='21'){
		$this->m_FtpHost 	= $p_FtpHost;
		$this->m_FtpUserName=  $p_FtpUserName;
		$this->m_FtpUserPass=  $p_FtpUserPass;
		$this->getStream();
		$this->connect();
	} //End function __construct()

	public function __destructor(){
		$this->disconnect();
	} // End function __distruct()

	// =================================================================
	public function connect(){
		if (isset($this->m_FtpStream)){
			if (isset($this->m_FtpUserName) AND isset($this->m_FtpUserPass)){
				if (@ftp_login($this->m_FtpStream, $this->m_FtpUserName, $this->m_FtpUserPass)){
				}else{
					$this->Disconnect($this->m_FtpStream);
					throw new constructException('No connection could bee made..');
				}
			}else{
				throw new constructException('Connection could not been made. User or/and password missing');
			}
		}else{
			throw new constructException('No connection avalible');
		}
	} //End function connect()

	public function disconnect(){
		ftp_close($this->m_FtpStream);
	} // End function disconnect()
// =================================================================
	public function setCurrentDir($p_dir=false) {
		if ($p_dir==true){
			ftp_chdir($this->m_FtpStream, $p_dir);
		}else{
			throw new cunstructException('No current dir could bee set!');
		}
		$this->m_currentDir = ftp_pwd($this->m_FtpStream);
		return $this->m_currentDir;
	}

	public function getCurrentDir(){
		return ftp_pwd($this->m_FtpStream);
	} // End function getCurrentDir()

	public function getStream(){
		if(isset($this->m_FtpHost) AND !empty($this->m_FtpHost)){
			if($this->m_FtpStream = ftp_connect($this->m_FtpHost)){
				return $this->m_FtpStream;
			}else{
				throw new constructException('No Ftp hostname or adress has been given');
			}
		}else{
			throw new constructException('No Ftp hostname or adress has been given');
		}
	} // End function getStream()

	public function getStreamStatus (){
		if(isset($this->m_FtpStream) AND !is_array($this->m_FtpStream)){
			return true;
		}else{
			return false;
		}
	} // End function getStreamStatus()

public function getaListDirFiles ($p_Dir='',$raw = false){
		if(empty($p_Dir) AND !empty($this->m_currentDir)){
			$p_Dir = $this->m_currentDir;
		}
			
		$func	= ($raw == false) ? 'ftp_nlist' : 'ftp_rawlist';
		$chk	= $func ($this->m_FtpStream, $p_Dir);
		if (is_array ($chk)){
			sort($chk);
			$arr= array();
			$count='';
			foreach ($chk as $file){
				if ($this->exsistDir($file)){
					$count++;
					$arr['dir'][$count]=($raw == false) ? str_replace ($p_Dir . '/', '', $file) : $file;
				}
			}
			$count='';
			foreach ($chk as $file) {
				if (!$this->exsistDir($file)) {
					$count++;
					$arr['file'][$count]['name']=($raw == false) ? str_replace ($p_Dir . '/', '', $file) : $file;
					$arr['file'][$count]['size']=$this->getFileSize($file);
					//$arr['file'][$count]['chmod']=ftp_chmod($this->m_ftpConn,'',$file);
					$arr['file'][$count]['lastmodi']=date("d-m-Y-H:i:s",ftp_mdtm($this->m_FtpStream,$file));
				}
				}
				return $arr;
			}
		throw new constructException('Connection could not been made. User or/and password missing');
	} // End function getaListDirFiles()

	public function getaList($p_Path=''){
		return (!empty($p_Path)) ? ftp_nlist($this->m_FtpStream,$p_Path) : false;
	} //End function getaList()

	public function getFileSize($p_File='',$int=false){
		if(!empty($p_File)){
			$size = ftp_size($this->m_FtpStream,$p_File);
			if($size == -1){
				$size='****';
			}else{
				if(!($int)){
					if ($size < 1024){
						return round($size,2).' bytes';
					}
					elseif ($size < (1024*1024)){
						return round(($size/1024),2).' KB';
					}
					elseif ($size < (1024*1024*1024)){
						return round((($size/1024)/1024),2).' MB';
					}
					elseif ($size < (1024*1024*1024*1024)){
						return round(((($size/1024)/1024)/1024),2).' GB';
					}
					elseif ($size < (1024*1024*1024*1024*1024)){
						return round((((($size/1024)/1024)/1024)/1024),2).' TB';
					}
				}
			}return $size;
		}else{
			throw new constructException('No file has ben given');
		}
	} // End function getFileSize()

	// =================================================================
	public function changeChmod($p_Path='',$p_Chmod='0'){
		if(!empty($p_Path) AND $p_Chmod != '0'){ //TODO controle of bestand nog bestaat!
			if ( @ftp_chmod($this->m_FtpStream, $p_Chmod, $p_Path)){
				return true;
			}else{
				throw new ftpException('Error accured at ftp chmod');
			}
		}else{
			throw new ftpException('No correct File or correct Chmod has been given');
		}
	} // End function changeChmod()

	public function deleteFile($p_File=''){
		if(!empty($p_File)){
			if(@ftp_delete($this->m_FtpStream ,$p_File)){
				return true;
			}else{
				throw new ftpException('Error. can\'t delete '. $p_File);
			}
		}else{
			throw new ftpExeption('No file has been given in function delteFile');
		}
	} //End function deleteFile()

	public function renameDirFile($p_OldName='', $p_NewName=''){ // '/dir1/dir2/', /dir1/dir3/
		if(!empty($p_OldName) AND !empty($p_NewName)){
			if (ftp_rename($this->m_FtpStream, $p_OldName, $p_NewName)){
				return TRUE;
			}else{
				throw new ftpException('Folder couldnot been renamed');
			}
		}else{
			throw new ftpException('No new or old folder name has been given');
		}
	} // End function renameDirFile()
	
function DeleteDirRecursive($p_Path) {
 	if($this->getStreamStatus()){
		$list=$this->getaList($p_Path);
		if ($list[0] != $p_Path ){
	        $path .= ( substr($p_Path, strlen($p_Path)-1, 1) == "/" ? "" : "/" );
	        foreach ($list as $item) {
		        if ($item != $p_Path.".." && $item != $p_Path.".") {
		            $this->DeleteDirRecursive($item);
		        }
	        }
			if (ftp_rmdir ($this->m_FtpStream, $p_Path)) {
				return true;
	        }else {
	            throw new ftpException('There was a problem while deleting '.$p_Path);
	        }
	    }else {
	        if (ftp_delete($this->m_FtpStream, $p_Path)) {
	            return true;
	        } else {
	            throw new ftpException('There was a problem while deleting'. $p_Path );
	        }
	    }
 	}else{
 		throw new ftpException('NO connection');
 	}
}

	public function moveFileDir($p_OldName='', $p_NewName=''){
		if(!empty($p_OldName) AND !empty($p_NewName)){
			if (ftp_rename($this->m_FtpStream, $p_OldName, $p_NewName)){
				return TRUE;
			}else{
				throw new ftpException('Folder could not been moved');
			}
		}else{
			throw new ftpException('No new or old folder location has been given');
		}
	} //End function moverFileDir()

	public function putFile($p_RemoteFile, $p_LocalFile, $p_Type = FTP_ASCII){
		if($chk = ftp_put($this->streams[$StreamName], $p_RemoteFile, $p_LocalFile, $p_Type)){
			return (file_exists ($p_LocalFile) && ($p_Type == FTP_ASCII || $p_Type == FTP_BINARY) && $chk) ? $chk : false;
		}else{
			throw new ftpException('File could not been send to the webserver ');
		}
		
	} // End function putFile()

	public function exsistDir($dir) {
		if (@ftp_chdir($this->m_FtpStream, $dir)){
			@ftp_chdir($this->m_FtpStream, '..');
			return true;
		}else{
			return false;
		}
	} // End function exsistDir()

	public function getFile($p_File,$p_Destination = "") {
		if($p_Destination == ""){
			$p_Destination = $this->m_downloadDir;
		}
		if(!empty($p_File)){
			$ok=true;
			if($this->m_resumeDownload) {
				$fp = @fopen($p_Destination . $p_File, "a+");
				$ok = @ftp_fget($this->m_FtpStream,$fp,"$p_File",1, filesize($p_Destination . $p_File));
			} else {
				$fp = @fopen($p_Destination . $p_File, "w+");
				$ok = @ftp_fget($this->m_FtpStream,$fp,$this->m_currentDir .'/'. $p_File,1);
			}
			fclose($fp);
			return $ok;
		}else{
			throw new ftpException('No file name has been given');
		}
	} // End function getFile()

	public function downloadFile($p_File){
		$fileStream = "";
		if($this->getFile($p_File)) {
			header("Content-type: application/octet-stream");
			header("Content-disposition:attachment;filename=\"". $p_File."\"");
			header("Pragma: no-cache");
			header("Expires: 0");
			$data = readfile($this->m_downloadDir . $p_File);
			$i=0;
			while ($data[$i] != "")
			{
				$fileStream .= $data[$i];
				$i++;
			}
			unlink($this->m_downloadDir . $p_File);
			echo $fileStream;
			//exit;
		} else {
			return false;
		}
	} // End function downloadFile()
} // END CLASS CLSFTP




//XXX Example
/*
 $obj = new clsFtp('andreaswarnaar.nl','phphulp','hulpphp');
 $obj->setCurrentDir('/cssplay'); // XXX werkt
 //print $obj->getCurrentDir();
 print '<PRE>';
 print_r($obj->getaListDirFiles());
 print '</PRE>';
 */
 --------------------------------------------------------------------------------------------------
// Class name:  	ftpException
// Dependency:		none
// Dependent files:	clsFtp.php			
// State:			protoype 
// --------------------------------------------------------------------------------------------------

class ftpException extends Exception{
    public $m_Output;
    function __construct($p_Message){
        parent::__construct($p_Message);
                $this->m_Output ='
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <title>Exception handler</title>
 <link rel="stylesheet" type="text/css" href="style.css" />
 <script type="text/javascript" src="popup.js" ></script>
</head>
<body>
<div id="popupcenterbg"></div>
 <div id="popupcenter">
  <table width="100%" height="80%"><tr><td valign="middle" align="center">
  <div id="popup"><div class="bar"><table><tr><td align="left">'.Error.'</td><td 
  align="right"><a onclick="closepopup();" href="#nogo"" > X </a></td></tr></table></div>'."\r\n".'
  <div class="PopupText">Error: '.$this->getMessage().'<br />
  Code: '.$this->getCode().'<br />
  File: '.$this->getFile().'<br />
  Line: '.$this->getLine().'<br /></div></div>
  </td></tr></table>
 </div>'."\r\n".'

</body>
</html>';
        
    } // End function __construct();
    function Report(){
        return $this->m_Output;
    } // End function getReport()
}

//XXX Example
try{
 $obj = new clsFtp('andreaswarnaar.nl','phphulp','hulpphp');
 $obj->setCurrentDir('/cssplay'); // XXX werkt
 //print $obj->getCurrentDir();
 print '<PRE>';
 print_r($obj->getaListDirFiles());
 print '</PRE>';
 $obj->deleteFile('DIT IS EEN VOOR BEELD VAN DE EXCEPTION HANDLER> ');
}catch( ftpException $e){
	print $e->Report();
}
?>
### popup.js ### 

function closepopup() {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById('popupcenter').style.visibility = 'hidden';
		document.getElementById('popupcenterbg').style.visibility = 'hidden';
	}
	else {
		if (document.layers) { // Netscape 4
			document.hidepage.visibility = 'hidden';
		}else { // IE 4
			document.all.hidepage.style.visibility = 'hidden';
		}
	}
}

### style.css ###
#popupcenter{
	top:0px;
	left:0px;
	width:100%;
	height:100%;
	position:absolute;
}
#popupcenterbg{
top:0px;
	left:0px;
	width:100%;
	height:100%;
	background:#666666;
	filter:alpha(opacity=50);
	-moz-opacity:.50;
	opacity:.50;
	position:absolute;
	z-index:0;
	}
#popupcenter2{
	width:400px;
	height:100px;
    margin-top:auto;
    margin-left:auto;
    margin-right:auto;
	margin-bottom:auto;
}
#popup {
    margin-left:auto;
    margin-right:auto;
    width: 500px;
    border: 2px solid #999999;
    background-color: #FFFFFF;
	position:static;
	

}
#popup .bar{
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 11px;
    color: #FFFFFF;
    background-color: #000033;
    display: block;
    width:auto;
}
#popup .bar a:link, {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 9px;
    color: #FFFFFF;
    background-color: #000033;
}
#popup .bar table{
    border-top-width: 0px;
    border-right-width: 0px;
    border-bottom-width: 0px;
    border-left-width: 0px;
    border-top-style: none;
    border-right-style: none;
    border-bottom-style: none;
    border-left-style: none;
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 11px;
    line-height: 10px;
    color: #FFFFFF;
    text-decoration: none;
    width: 100%;
}
#popup .PopupText{
    background:#FFFFFF;
    font-family: Arial, Helvetica, sans-serif;
    font-size:13px;
    text-align:left;
    padding:2px;
}
#popup .PopupText a:link, #popup .PopupText a:visited , #popup .PopupText a:hover  {
    font-family:Verdana, Arial, Helvetica, sans-serif;
    font-size:11px;
    color:#3366CC;
    text-decoration:none;
}
#popup .PopupText a:hover {
    font-family:Verdana, Arial, Helvetica, sans-serif;
    font-size:11px;
    color:#6600FF;
    text-decoration:none;
}