<?php /*
=====================================================================

  functions_afb.inc.php
	
	Functions specific to this application.

===================================================================== */



//------------------------------------------------------------------------
//afbGetShares
function afbGetShares() {
	//this function returns the shares available to the user
	global $db;
	global $share_perms;
	
	//setup shares
	$shares = array();
	
	$sql = "SELECT * FROM `".TABLE_PREFIX."shares` ORDER BY `share_name`";
	$result = $db->Execute($sql);
	while (!$result->EOF){
		//get perms based on account
		$perms = afbGetSharePerms($result->fields['share_id']);
		//set share perms for this share
		$share_perms[$result->fields['share_id']] = $perms;
		//check if we're displaying it
		if ($perms['list'] || $perms['write']) {
			//read or upload ability
			$shares[] = array(
				'id'=>$result->fields['share_id'],
				'name'=>htmlspecialchars(stripslashes($result->fields['share_name'])),
				'description'=>htmlspecialchars(stripslashes($result->fields['share_description'])),
				'dir'=>stripslashes($result->fields['share_dir']),
				'perm_list'=>$perms['list'],
				'perm_write'=>$perms['write'],
				'perm_download'=>$perms['download'],
				'perm_modify'=>$perms['modify']
			);
		}
		//next share please
		$result->MoveNext();
	}
	//return some love.
	return $shares;
	
} // end afbGetShares function

//------------------------------------------------------------------------
//afbGetShare
function afbGetShare($id) {
	//this function returns only one share
	global $db;
	
	$share = false;
	
	$sql = "SELECT * FROM `".TABLE_PREFIX."shares` WHERE `share_id`='".addslashes($id)."' LIMIT 0,1";
	if ($result = $db->Execute($sql)){
		//get perms based on account
		$perms = afbGetSharePerms($result->fields['share_id']);
		//check if we're displaying it
		if ($perms['list'] || $perms['write']) {
			//read or upload ability
			$share = array(
				'id'=>$result->fields['share_id'],
				'name'=>htmlspecialchars(stripslashes($result->fields['share_name'])),
				'description'=>htmlspecialchars(stripslashes($result->fields['share_description'])),
				'dir'=>stripslashes($result->fields['share_dir']),
				'perm_list'=>$perms['list'],
				'perm_write'=>$perms['write'],
				'perm_download'=>$perms['download'],
				'perm_modify'=>$perms['modify']
			);
			
			//return some love.
			return $share;
		}
	}
	return false;
} // end afbGetShare function

//------------------------------------------------------------------------
//afbGetSharePerms
function afbGetSharePerms($share_id) {
	global $afbAccount;
	global $db;
	
	if ($afbAccount) {
		$account_id = $afbAccount->account['account_id'];
	} else {
		$account_id = 0;
	}
	
	//set default perms
	$perms = array('list'=>false,'download'=>false,'write'=>false,'modify'=>false);
	
	if ($afbAccount->account['account_admin'] == 'yes') {
		$perms = array('list'=>true,'download'=>true,'write'=>true,'modify'=>true);
		return $perms;
	}
	
	//get perms based on account
	$sql = "SELECT * FROM `".TABLE_PREFIX."accounts_has_perms` WHERE `account_id`='".$account_id."' AND `share_id`='".$share_id."'";
	$result = $db->Execute($sql);
	$recordcount = $result->RecordCount();
	if ($recordcount > 0) {
		if ($result->fields['perm_list'] == 'yes') {
			$perms['list'] = true;
		}
		if ($result->fields['perm_download'] == 'yes') {
			$perms['download'] = true;
		}
		if ($result->fields['perm_write'] == 'yes') {
			$perms['write'] = true;
		}
		if ($result->fields['perm_modify'] == 'yes') {
			$perms['modify'] = true;
		}
	}
	
	return $perms;
	
} //end afbGetSharePerms function

//------------------------------------------------------------------------
//afbLogit
function afbLogit($action,$data='',$share_id=0) {
	global $db;
	global $afbAccount;
	
	$account_id = 0;
	if ($afbAccount) {
		$account_id = $afbAccount->account['account_id'];
	}
	
	$sql = "INSERT INTO `".TABLE_PREFIX."log` (
		`log_action`,
		`log_data`,
		`account_id`,
		`share_id`,
		`log_timestamp`,
		`log_ip`
	) VALUES (
		'".addslashes($action)."',
		'".addslashes($data)."',
		'".$account_id."',
		'".$share_id."',
		'".GMT_TIME."',
		'".IP."'
	)";
	if ($db->Execute($sql) === false) { 
		return false;
	}
	return true;
} //end afbLogit function

//------------------------------------------------------------------------
//afbGetListing
function afbGetListing($share,$path='') {
	$path = TieString($path,'/','/');
	$path = str_replace('//','/',$path);
	$returns = array();
	
	if (CheckFolder($share['dir'],$path) && $share['perm_list']) {

		//spit out the contents!
		$fullpath = $share['dir'].TieString(trim($path,'/'),'','/');
		$dirs = array();
		$files = array();
		$total_size = 0;
		$item_count = 0;
		$max = 0;
		$dh = @opendir($fullpath);
		while (false !== ($file=@readdir($dh))) {

			if (substr($file,0,1)!=".") {  #skip anything that starts with a '.' i.e.:('.', '..', or any hidden file)
				if (is_dir($fullpath.$file)) {
					$dirs[]=$file;   #put directories into dirs[] and append a '/' to differentiate
				} else {
					$files[]=$file;   #everything else goes into files[]
				}
			}
		}
		@closedir($dh);

		if ($files) {
			natcasesort($files); #natural case insensitive sort
		}
		if ($dirs) {
			natcasesort($dirs);
		}
											
		//OUTPUT DIRS
		foreach ($dirs as $key => $value) {
			if (CheckFolder($share['dir'],$path . $value)) {
				$img = '';
				
				//check for folder.jpg
				if (is_file(TieString($fullpath.$value,'','/').'Folder.jpg')){
					$img = 'index.php?preview='.urlencode(TieString($path,'','/').$value.'/Folder.jpg').'&share='.urlencode($share['id']).'&type=2';
				}
				
				$returns['dirs'][] = array(
					'name'=>$value,
					'path'=>trim($path,'/').'/'.$value.'/',
					'unique'=>md5($share['id'].trim($path,'/').'/'.$value),
					'thumbnail'=>$img
				);
			}
		} //end for

		//OUTPUT FILES
		foreach ($files as $key => $value) {
			//$value = htmlspecialchars(htmlentities($value));
			$size = sprintf("%u", @filesize($fullpath.$value));
			$total_size += $size;
			//$total_size += $size;
			if (CheckFile($share['dir'],$fullpath.$value)) {
				$link = false;
				if ($share['perm_download']){
					$link = 'index.php?share='.$share['id'].'&path='.rawurlencode(trim($path,'/').'/'.$value);
				}
				
				//determine if is an img for thumbnails
				$ext = strtolower(GetExt($value));
				$img = '';
				
				switch ($ext) {
					//audio files
					case 'mp3':
					case 'mp2':
					case 'wav':
					case 'wma':
					case 'm4a':
						$category = 'audio';
						break;
					
					//image files
					case 'jpg':
					case 'gif':
					case 'png':
						$category = 'image';
						//link to a preview img
						$img = 'index.php?preview='.urlencode(TieString($path,'','/').$value).'&share='.urlencode($share['id']).'&type=2';
						break;
					
					//video files
					case 'avi':
					case 'wmv':
					case 'asf':
					case 'divx':
					case 'mpg':
					case 'mp4':
					case 'qt':
					case 'rm':
					case 'mov':
					case 'mpeg':
						$category = 'video';
						//search for a tbn file, which is really a jpg file.
						$tbnfile = RemoveExtension($fullpath).'.tbn';
						$tbnfile2 = RemoveExtension(TieString($path,'','/').$value).'.tbn';
						if (file_exists($tbnfile)){
							$img = 'index.php?preview='.urlencode($tbnfile2).'&share='.urlencode($share['id']).'&type=2';
						}
						break;
						
				} //end switch
				
				$returns['files'][] = array(
					'name'=>$value,
					'path'=>trim($path,'/').'/'.$value,
					'type'=>strtolower(GetExt($value)),
					'size'=>GetSize($size),
					'unique'=>md5($share['id'].trim($path,'/').'/'.$value),
					'thumbnail'=>$img,
					'category'=>$category
				);
			}
		}
						
	}
	return $returns;
		
} //end afbGetListing

//------------------------------------------------------------------------
//afbGetPreviewDetails
function afbGetPreviewDetails($share,$path='') {
	$path = TieString($path,'/');
	$path = str_replace('//','/',$path);
	$fullpath = $share['dir'].trim($path,'/');
	
	//check if it's a file or a dir.
	//----------------------------------------------------
	//dir
	if (is_dir($fullpath)) {
		//is a dir
		if (CheckFolder($share['dir'],$path) && $share['perm_list']) {
			//we're allowed to investigate this.
			
			$dirs = 0;
			$files = 0;
			$total_size = 0;
			$dh = @opendir($fullpath);
			while (false !== ($file=@readdir($dh))) {
				if (substr($file,0,1)!=".") {  #skip anything that starts with a '.' i.e.:('.', '..', or any hidden file)
					if (is_dir($fullpath.$file)) {
						$dirs++;   #put directories into dirs[] and append a '/' to differentiate
					} else {
						$files++;   #everything else goes into files[]
						$size = sprintf("%u", @filesize($fullpath.$file));
						$total_size += $size;
					}
				}
			}
			@closedir($dh);
			
			//check for Folder.jpg
			if (is_file(TieString($fullpath,'','/').'Folder.jpg')){
				$preview_link = 'index.php?preview='.urlencode(TieString($path,'','/').'Folder.jpg').'&share='.urlencode($share['id']);
			}
			
			return array(
				'type'=>'dir',
				'size'=>GetSize($total_size),
				'name'=>GetFilename($fullpath),
				'dirs'=>$dirs,
				'files'=>$files,
				'preview'=>$preview_link
			);
			
		}
		
	//----------------------------------------------------
	//File
	} elseif (is_file($fullpath)) {
		//is a file
		if (CheckFile($share['dir'],$fullpath) && $share['perm_list']) {
			//we're allowed to return something.
			$ext = strtolower(GetExt($fullpath));
			
			switch ($ext) {
				//audio files
				case 'mp3':
				case 'mp2':
				case 'wav':
				case 'wma':
				case 'm4a':
					$category = 'audio';
					break;
				
				//image files
				case 'jpg':
				case 'gif':
				case 'png':
					$category = 'image';
					//link to a preview img
					$preview_link = 'index.php?preview='.urlencode($path).'&share='.urlencode($share['id']);
					//try to get dimensions of file...
					$data = getimagesize($fullpath); //[0] = w, [1] = h, [2] = type, [3] = attr
					if ($data[2] > 0){
						$w = $data[0];
						$h = $data[1];
						$dimensions = $w.' x '.$h;
					}
					
					break;
				
				//video files
				case 'avi':
				case 'wmv':
				case 'asf':
				case 'divx':
				case 'mpg':
				case 'mp4':
				case 'qt':
				case 'rm':
				case 'mov':
				case 'mpeg':
					$category = 'video';
					//search for a tbn file, which is really a jpg file.
					$tbnfile = RemoveExtension($fullpath).'.tbn';
					$tbnfile2 = RemoveExtension($path).'.tbn';
					if (file_exists($tbnfile)){
						$preview_link = 'index.php?preview='.urlencode($tbnfile2).'&share='.urlencode($share['id']);
					}
					break;
					
			} //end switch
			
			if ($share['perm_download']){
				$download_link = 'index.php?download='.urlencode($path).'&share='.urlencode($share['id']);
			}
			
			return array(
				'type'=>'file',
				'ext'=>$ext,
				'size'=>GetSize(sprintf("%u", @filesize($fullpath))),
				'name'=>RemoveExtension(GetFilename($fullpath)),
				'preview'=>$preview_link,
				'category'=>$category,
				'download'=>$download_link,
				'dimensions'=>$dimensions
			);
			
		}
	} //end type check
	
	return false;
} //end afbGetPreviewDetails

//------------------------------------------------------------------------
//CheckFolder
function CheckFolder($share_root='/',$path='/') {
	global $blacklist_dirs;
	
	$fullpath = str_replace('//','/',TieString($share_root,'','/').trim($path,'/').'/');
	
	//check for traversal
	if (strpos($path,'../')!==false){
		return false;
	}
	
	if (is_dir($fullpath)) {
		//get all directory names
		$dirs = explode('/',str_replace($share_root,'',$path));
		for ($x=0;$x<count($dirs);$x++) {
			//check blacklist
			if (@in_array(strtolower($dirs[$x]),$blacklist_dirs)) {
				return false;
			}
		}
		return true;
	} else {
		return false;
	}
} //end function

//------------------------------------------------------------------------
//CheckFile
function CheckFile($share_root='/',$path='',$ignore_bl=false) {
	global $blacklist_types;
	global $blacklist_files;
	
	
	
	//check for traversal
	$p = str_replace($share_root,'',$path);
	if (strpos($p,'../')!==false){
		return false;
	}
	
	if (is_file($path)) {
		//Get filename
		$file = strtolower(GetFilename($path));
		//check against blacklist				
		if (@in_array(strtolower($file),$blacklist_files)) {
			return false;
		}
		
		//Get extension
		if (!$ignore_bl){
			$ext = GetExt($file);
			if (@in_array(strtolower($ext),$blacklist_types)) {
				return false;
			}
		}
		
		return true;
	} else {
		return false;
	}
} //end function

//------------------------------------------------------------------------
//getLangTerm - gets language term from language array.
function getLangTerm($string,$escapechar="'"){
	global $LANGUAGE;
	
	$term = $LANGUAGE[strtolower($string)];
	if (strlen(trim($term)) == 0){
		$term = ucwords(strtolower($string));
	}
	
	if ($escapechar === true){
		$term = addslashes($term);
	} elseif (strlen($escapechar) > 0){
		$term = str_replace($escapechar,'\\'.$escapechar,$term);
	}
	return htmlspecialchars($term);
} //end getLangTerm

?>