Location: PHPKode > scripts > Ramui web hosting directory script > Ramui web hosting directory script/gb/admin/include/clstemplate.php
<?php
/*
Copyright (c) 2011 http://ramui.com. All right reserved.
This product is protected by copyright and distributed under licenses restricting copying, distribution. Permission is granted to the public to download and use this script provided that this Notice and any statement of authorship are reproduced in every page on all copies of the script.
*/
class template extends clsmain
{
private $template_path;
private $dir;

function __construct()
{
        parent::__construct();
        $this->template_path=$_SERVER['DOCUMENT_ROOT'].fw_get_docroot().'gb/templates/';
        $this->dir=((isset($_GET['dir'])&&($_GET['dir']!==''))? $_GET['dir'] : $this->template_path);
        if(strpos($this->dir,$this->template_path)!==0){$this->dir=$this->template_path;}
}
private function set_clipboard()
{
        $source=fw_strip_slashes(rawurldecode($_POST['source']));
		if(setcookie('fw_clipboard',$source)){
			$arg="'File / Directory already exist!',''";
			echo '<a title="'.$source.'" href="#" onclick="javascript:fwPast('.$arg.')"><img src="images/past.gif" /></a>';}
		else{
			$arg="'Sorry! Fail to copy.',''";
			echo '<a title="Fail to copy" href="#" onclick="javascript:fwPast('.$arg.')"><img src="images/pastempty.gif" /></a>';}
		exit;
}
private function show_uploadlist($message='')
{
        $clipboard=$_COOKIE['fw_clipboard'];
		$clipmsg='';
		if(!empty($clipboard)){
			if(strpos($clipboard,$this->template_path)!==0){$clipboard='';}
			else{
				$x=(substr($clipboard,-1)=='/');
				$pos=$x? strrpos(substr($clipboard,0,-1),'/') : strrpos($clipboard,'/');
				$name=($x)? substr($clipboard,$pos+1,-1) : substr($clipboard,$pos+1);
				if(file_exists($this->dir.$name)){$clipmsg='File / Directory already exist!';}
			}
		}
		if(!empty($clipboard)){
			$clipdir=substr($clipboard,0,$pos+1);
			if($x&&(strpos($this->dir,$clipboard)===0)){$clipmsg='Unable to past parent folder under child.';}
			else{if($this->dir===$clipdir){$clipmsg='File / Directory already exist!';}}
		}
		if(empty($clipboard)){
			$arg="'Empty ClipbBoard',''";
			$cliplink='<a title="Empty Clipboard" href="#" onclick="javascript:fwPast('.$arg.')"><img src="images/pastempty.gif" /></a>';}
		else{
			$arg="'".fw_php2javascript($clipmsg)."','".fw_php2javascript($this->dir)."'";
			$cliplink='<a title="'.$clipboard.'" href="#" onclick="javascript:fwPast('.$arg.')"><img src="images/past.gif" /></a>';
		}
		$caption=substr($this->template_path,1,-1);
        $this->build_head($caption, '<script type="text/javascript" src="script/template.js"></script>');
        if(!empty($message)){echo '<div id="feedback" style="margin:0;padding:0;">'.$message.'</div>';}
		echo '<table class="detail" style="width:100%; margin:0 0 10px 0;">';
		echo '<tr><td colspan="3" style="background:#e0e0e0;padding:5px;border-bottom:1px solid #c0c0c0;"><div style="float:left;clear:left;"><a href="index.php?qur=7M">'.$caption.'</a> / ';
        if($this->dir!==$this->template_path){
                $path_array=explode('/',substr($this->dir,strlen($this->template_path),-1));
                $links=$this->template_path;
                for($i=0; $i<count($path_array); $i++){
                       $links.=$path_array[$i].'/';
                       echo (($i==count($path_array)-1)? $path_array[$i] : '<a href="index.php?qur=7M&dir='.$links.'">'.$path_array[$i].'</a>/');}}
        echo '</div><div id="clipboard">'.$cliplink.'</div></td></tr>';
		echo '<tr><td colspan="3"><img title="Create new folder" src="images/new_folder.gif" /><a href="javascript:fwNewFolder(\''.fw_php2javascript($this->dir).'\')">Create new:</a></td></tr>';
        if($handle=opendir($this->dir)){
			while (false !== ($item = readdir($handle))){if($item != "." && $item != ".."){
				if(is_dir($this->dir.$item)){
					$arg="'".fw_php2javascript(($this->dir).$item.'/')."'";
					$dirs.='<tr onMouseOver="this.className=\'highlight\'" onMouseOut="this.className=\'normal\'"><td><img src="images/folder.gif"/><a href="index.php?qur=7M&dir='.$this->dir.$item.'/">'.$item.'</a></td><td></td><td style="text-align:center">';
					$dirs.='<a style="color:#335599;" href="#" onclick="return fwCopy('.$arg.');">Copy</a> | ';
					$dirs.='<a style="color:#339955;" href="#" onclick="return fwRename('.$arg.');">Rename</a> | ';
					$dirs.='<a style="color:#993322;" href="#" onclick="return fwDelete('.$arg.');">Delete</a></td></tr>';
				}
				else{
					$filename=$this->dir.$item;
					$arg="'".fw_php2javascript($filename)."'";
					$extension=substr($item,strrpos($item,'.')+1);
					$img='images/file_inactive.gif';
					$open_url='';
//If imagefile.
					if(getimagesize($filename)!==false){
						$open_url='javascript:fwOpenImage(\''.urlencode(fw_abs_to_url($filename)).'\')';
						$img='images/file_browser.gif';}
//If editable file.
					if(array_search($extension,array('php','html','htm','txt','css','js','htaccess'))!==false){
						$open_url='javascript:fwOpenEdit(\''.urlencode($filename).'\')';
						$img='images/file_active.gif';}
					$files.='<tr onMouseOver="this.className=\'highlight\'" onMouseOut="this.className=\'normal\'"><td><img src="'.$img.'"/>'.(($open_url=='')? $item : '<a href="'.$open_url.'">'.$item.'</a>').'</td><td>'.round(filesize($filename)/1024,1).'KB </td><td style="text-align:center;">';
					$files.='<a style="color:#335599;" href="#" onclick="return fwCopy('.$arg.');">Copy</a> | ';
					$files.='<a style="color:#339955;" href="#" onclick="return fwRename('.$arg.');">Rename</a> | ';
					$files.='<a style="color:#993322;" href="#" onclick="return fwDelete('.$arg.');">Delete</a></td></tr>';
				}
			}}
			closedir($handle);
		}
		echo $dirs.$files;
        echo '<tr><td colspan="3" style="background:#e0e0e0;">';
        echo '<form name="frmUpload" enctype="multipart/form-data" action="index.php?qur=7M1&dir='.urlencode($this->dir).'" method="POST" style="float:right; margin:0; color:#000000;" onSubmit="return fwCheckSubmit(this);">';
        echo '<input type="hidden" name="MAX_FILE_SIZE" value="200000" />';
        echo 'Choose a file to upload: <input name="file" type="file" style="padding-left:5px; width:180px; font-size:11px; color:#666666;"/>&nbsp;&nbsp;<input name="submit" type="submit" value="Upload File" style="width:80px; font-size:11px; color:#333333;"/>&nbsp;<input type="reset" value="Reset" style="width:80px; font-size:11px; color:#333333;"></form>';
        echo '</td></tr>';
        echo '</table></div>';
        $this->build_footer();
}

private function delete_file()
{
        $filename=fw_strip_slashes(rawurldecode($_GET['source']));
		if(strpos($filename,$this->template_path)!==0){exit;}
        $x=(substr($filename,-1)=='/');
		if($x){$filename=substr($filename,0,-1);}
		if(!file_exists($filename)){$message='<div style="margin:5px; color:red;">Source not found!</div>';}
		else{
			$this->dir=substr($filename,0,strrpos($filename,'/')+1);
			if($x){$message=(($this->rec_delete_folder($filename))? '<div style="margin:5px; color:green;">Directory is successfully deleted!</div>' : '<div style="margin:5px; color:red;">Sorry! Unable to delete directory. Please check file permission.</div>');}
			else{$message=(@unlink($filename))? '<div style="margin:5px; color:green;">File is successfully deleted!</div>':'<div style="margin:5px; color:red;">Sorry! Unable to delete file. Please check file permission.</div>';}}
        $this->show_uploadlist($message);
}

private function rec_delete_folder($folderPath )
{
        if(is_dir($folderPath)){
                 foreach(scandir($folderPath) as $value){
                       if($value != "." && $value != ".." ){
                                 $value = $folderPath . "/" . $value;
                                 if(is_dir($value)){$this->rec_delete_folder($value);}
                                 elseif(is_file($value)){@unlink ( $value );}
                       }
                 }
                 return rmdir ( $folderPath );
        }
        else{return false;}
}

private function recurse_copy($src,$dst) {
        $dir = opendir($src);
        @mkdir($dst);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if ( is_dir($src . '/' . $file) ) {
                    $this->recurse_copy($src . '/' . $file,$dst . '/' . $file);
                }
                else {
                    copy($src . '/' . $file,$dst . '/' . $file);
                }
            }
        }
        closedir($dir);
}

private function check_filename(&$name)
{
		$pattern = '/.[a-zA-Z0-9][a-zA-Z0-9\-\_\.]*\Z/';
        $arr=explode('/',$name);
        $newname=array();
        for($n=0; $n<count($arr); $n++){
            $s=trim($arr[$n]);
            $length=strlen($s);
            if(($length>50)||($length<1)){return false;}
			if(!preg_match($pattern, $s)){return false;}
            $newname[]=$s;}
        $name=implode('/',$newname);
        return true;
}
private function past()
{
		$dst=fw_strip_slashes(rawurldecode($_GET['dst']));
		$this->dir=$dst;
		$dst=substr($dst,0,-1);
		$clipboard=$_COOKIE['fw_clipboard'];
		setcookie('fw_clipboard','');
		$_COOKIE['fw_clipboard']='';
		if((strpos($clipboard,$this->template_path)!==0)||(empty($clipboard))){$message='<div style="margin:5px; color:red;">Source not found!</div>';}
		if(empty($message)){
			$x=(substr($clipboard,-1)=='/');
			if($x){$clipboard=substr($clipboard,0,-1);}
			if(!file_exists($clipboard)){$message='<div style="margin:5px; color:red;">Source not found!</div>';}
			$dst.='/'.substr($clipboard,1+strrpos($clipboard,'/'));
			if(file_exists($dst)){$message='<div style="margin:5px; color:red;">File / folder already exist!</div>';}
		}
		if(empty($message)){
			if($x){$this->recurse_copy($clipboard,$dst); $message='<div style="margin:5px; color:green;">Succesfully copy folder!</div>';}
			else{$message=((copy($clipboard,$dst))? '<div style="margin:5px; color:green;">Succesfully copy file!</div>' : '<div style="margin:5px; color:red;">Sorry! Unable to copy. Please check file permission.</div>');}
		}
		$this->show_uploadlist($message);
}
private function redirect()
{
		$url='index.php?qur=7M&dir='.$this->dir;
		@header("Location: $url");exit;
}

private function rename_file()
{
        $source=fw_strip_slashes(rawurldecode($_GET['source']));
        $dst=fw_strip_slashes(rawurldecode($_GET['dst']));
		$x=(substr($source,-1)=='/');
		if($x){$source=substr($source,0,-1);}
		$path=substr($source,0,1+strrpos($source,'/'));
		$this->dir=$path;
		$path=substr($path,0,-1);
		$dst=str_replace('../','./',$dst);
        for($i=0; $i<10; $i++){
            if(strpos($dst,'./')!==0){break;}
            $dst=substr($dst,2);
            $path=substr($path,0,strrpos($path,'/'));
            if(strpos($path.'/',$this->template_path)!==0){$message='<div style="margin:5px; color:red;">Sorry! Can\'t move over parent folder.</div>'; break;}
        }
		if(empty($message)){if($this->check_filename($dst)==false){$message='<div style="margin:5px; color:red;">Invalid file or folder name!</div>';}}
		$dst=$path.'/'.$dst;
		if(empty($message)){if(file_exists($dst)){$message='<div style="margin:5px; color:red;">File / folder already exists!</div>';}}
		if(!file_exists($source)){$message='<div style="margin:5px; color:red;">Source not found!</div>';}
		if(empty($message)){
            $path=substr($dst,0,strrpos($dst,'/'));
            if(!is_dir($path)){
                $b=@mkdir($path,0777,true);
                if(!$b){$message='<div style="margin:5px; color:red;">Sorry! Unable to create folder.</div>';}
            }
			if(empty($message)){$message=((rename($source,$dst))? '<div style="margin:5px; color:green;">Rename succesfull!</div>' : '<div style="margin:5px; color:red;">Sorry! Unable to rename. Please check file permission.</div>');}
		}
		$this->show_uploadlist($message);
}

private function new_folder()
{
        $name=fw_strip_slashes(rawurldecode($_GET['name']));
		$this->dir=fw_strip_slashes(rawurldecode($_GET['path']));
		$pattern = '/.[a-zA-Z0-9][a-zA-Z0-9\-\_\.]*\Z/';
		if(!preg_match($pattern, $name)){$message='<div style="margin:5px; color:red;">Invalid folder name! Please select different folder name.</div>';}
		else{
			$name=$this->dir.$name;
			if(is_dir($name)){$message='<div style="margin:5px; color:red;">Sorry! Folder already exist. Please select different folder name.</div>';}
			else{
				if(mkdir($name)){$message='<div style="margin:5px; color:green;">Folder has been created succesfully!</div>';}
				else{$message='<div style="margin:5px; color:red;">Sorry! Unable to create folder.</div>';}}
		}
        $this->show_uploadlist($message);
}

private function show_edit()
{
        $filename=fw_strip_slashes(rawurldecode($_GET['filename']));
        $str='<html><head><title>'.$filename.'</title><script type="text/javascript" src="../script/common.js"></script><script type="text/javascript" src="script/template.js"></script>';
		$str.='<style>
        <!--
        body, textarea{font-family:\'courier new\'; font-size:13px;line-height:140%;color:#333360;}
        body{height:100%;}
        a{ color:#0000ff;text-decoration:underline;font:500 12px tahoma;}
        a:hover{text-decoration:none;}
        -->
        </style></head>
        <body>
        <form name="frmEdit" style="margin:0; background:#dddddd; padding:0; min-width:600px; border:1px solid #cccccc; height:97%;" onSubmit="return(false);">
        <div style="background:#eeeeee url(\'images/bg.png\') repeat-x; padding:10px; clear:both; height:20px;">
        <div style="float:left; margin-bottom:10px;">
        <a href="javascript:fwSaveDocument(\''.fw_php2javascript($filename).'\');">Save</a> | <a href="javascript:window.close();">Close</a></div>
        <div id="feedback" style="float:right; clear:right;"></div>
        </div>
        <textarea style="width:100%; height:93%; border:none; padding:5px;" name="txtEdit" cols="20" rows="1" onClick="javascript:fwClearFeedback();">';
        $str.=htmlspecialchars(@file_get_contents($filename),ENT_QUOTES).'</textarea></form></body></html>';
        echo $str;
}

private function save_edit()
{
        $filename=trim(fw_strip_slashes(rawurldecode($_POST["filename"])));
        $content=trim(fw_strip_slashes(rawurldecode($_POST["content"])));
        if((strpos($filename,$this->template_path)===0)&&(file_exists($filename))){
                 if(@file_put_contents($filename,$content)===false){echo '<img src="images/close.gif" style="border:none;" /><span style="font-weight:600; color:red; margin-bottom:2px;">Unable to save file. Please check file permission.</span>';}
                 else{echo '<img src="images/right.gif" style="border:none;" /><span style="font-weight:600; color:green; margin-bottom:2px;">File has been updated.</span>';}
        }
}

public function get_query($query)
{
if ($this->validate_user()){
    switch ($query[1]) {
        case "1":
            $this->show_uploadlist($this->upload_file($this->dir));
        break;
        case "2":
            $this->delete_file();
        break;
        case "3":
            $this->show_edit();
        break;
        case "4":
            $this->save_edit();
        break;
        case "5":
            $this->log_out();
        break;
        case "7":
            $this->rename_file();
        break;
        case "8":
            $this->past();
        break;
        case "9":
            $this->set_clipboard();
        break;
        case "10":
            $this->new_folder();
        break;
        default :
            $this->show_uploadlist();
    }
}
else {if($query[1]!='4'){$this->log_in();}}
}
private function upload_file($path)
{
        if(!(isset($_POST['submit']))){exit;}
        if($_FILES["file"]["size"] > 200000){exit;}
        $err=$_FILES["file"]["error"];
        $message='<div style="margin:5px; color:red;">Upload fails! ';
        if ($err > 0){
               switch($err){
                     case '1':
                           $message.='php.ini max file size exceeded.';
                           break;
                     case '2':
                           $message.='max file size exceeded.';
                           break;
                     case '3':
                           $message.='file upload was only partial.';
                           break;
                     case '4':
                           $message.='no file was attached.';
                           break;
                     case '7':
                           $message.='file permission denied.';
                           break;
                     default :
                           $message.='Unexpected error occers.';}
                     $message.='</div>';
        }
        else{
               if (file_exists($path.$_FILES["file"]["name"])){
                     $message.='file already exist.</div>';}
               else{
                     @move_uploaded_file($_FILES["file"]["tmp_name"],$path. $_FILES["file"]["name"]);
                     $message='<div style="margin:5px; color:green;">File has been successfully uploaded.</div>';}
        }
        return $message;
}
}
?>
Return current item: Ramui web hosting directory script