<?php
	$autoStart = false;
	require_once('../../wiki.php');
	//error_reporting(E_ALL);
	
	
	//pass a file on to the client
	class passFile{
		
		//requires $_GET['o'] (owner) and $_GET['f'] (filename);
		function passFile(){
			global $rootDir;
			$owner =& $_GET['o'];
			$file =& $_GET['f'];
			
			$this->checkValue($owner);
			$this->checkValue($file);
			
			
			$path = $rootDir.'/userfiles/'.$owner.'/uploaded/'.str_replace('.','.wb~',$_GET['f']);
			if( is_file($path) ){
				$this->sendFile($path,$_GET['f']);
				return;
			}
			
			//try without the .wb~ for older files and files with safe extensions like .gz
			$path = $rootDir.'/userfiles/'.$owner.'/uploaded/'.$_GET['f']; 
			if( is_file($path) ){
				$this->sendFile($path,$_GET['f']);
				return;
			}
			$this->notFound();
		}
		
		function notFound(){
			header('HTTP/1.0 404 Not Found');
			die('404 Not Found '.$_GET['f']);
		}
		
		//send it
		function sendFile(&$path,&$reqName){
			global $rootDir;
			
			
			//$reqName = str_replace('.wb~','.',$reqName);
			
			
			// send the right headers
			// only avail as of php 4.3
			if( function_exists('mime_content_type') ){
				$mtype = mime_content_type($reqName);
				if ( $mtype != "" ) {
					header('Content-Type: ' . $mtype);
				}
			}
			
			
			//a little content negotiation
			//	send gz encoded version if it's available
			if( isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false) ){
				$gzPath = $path.'.gz';
				if( is_file($gzPath) ){
					
					header('Content-Encoding: gzip');
					header('Content-Disposition: attachment; filename='.$reqName);
					
					$fp = fopen($gzPath, 'rb');
					fpassthru($fp);
					exit;	
				}
			}
			
			//Send normal version
				header('Content-Length: ' . filesize($path));
				header('Content-Disposition: attachment; filename='.$reqName);
				
				$fp = fopen($path, 'rb');
				fpassthru($fp);
				exit;
		}
		
		function checkValue($value){
			if( empty($value) ){
				$this->notFound();
			}
			
			//$_GET[$key] = urldecode($_GET[$key]);
			$value = str_replace('\\','/',$value);
			if( strpos($value,'/') ){
				$this->notFound();
			}
			return true;
		}
	}
	
	new passFile();
