<?php

include("_config/addCfg.php");
include("_includes/addInc.php");

/*
 * The minibrowser functionality. this scans for files and folders, and sends them to the smarty template for displaying
*/

/*
 * local function to scan the specified directory and return propreties for each file.
 * Ipreffer this metod instead of using a "classic" scandir() because this results can get cached
 * 	if really needed, and so avoid any kind of interaction with the filesystem
*/
function scanDirectories($rootDir, $allowext=false) {
	global $CFG;

	$iconAssociations=$CFG['miniBrowser']['iconAssociations'];

	$return=[];

	$dirContent = scandir($rootDir);

	foreach($dirContent as $key => $content) {
		if ($content == '.' || $content == '..') continue;
		$ret=[];

		$path = $rootDir . '/' . $content;
		$path =cleanPath(str_replace('//','/',$path ));
		$ext = strtolower(substr($content, strrpos($content, '.') + 1));
		if(is_file($path) && is_readable($path)) {
			$ret['path']=$path;
			$ret['extension']=$ext;
			$ret['type']='';

			foreach($iconAssociations as $type=>$assocArr){
				if(in_array($ret['extension'],$assocArr)){
					$ret['type']=$type;
					break;
				}
			}

			$ret['file']=$content;
			$ret['is_file']=true;
		}elseif(is_dir($path) && is_readable($path)) {
			$ret['path']=$path.'/';
			$ret['file']=$content;
			$ret['is_file']=false;
		}
		$return[]=$ret;
	}

	// separate folders from files, so we will sort them independently
	$folders = Array();
	$files = Array();
	foreach($return as $r){
		if($r['is_file']){
			$files[] = $r;
		}else{
			$folders[] = $r;
		}
	}

	// folders should be first in list
	usort($files, function ($a, $b) {
		return strcasecmp($a['path'], $b['path']);
	});

	usort($folders, function ($a, $b) {
		return strcasecmp($a['path'], $b['path']);
	});

	return array_merge($folders, $files);
}

// cleanup the input path
$R['path'].='/';
$R['path']=cleanPath(str_replace('//','/',$R['path'] ));
$R['path']=str_replace('//','/',$R['path']);

if($R['path']=='/')$R['path']='';

// limit going up in the folder tree so we will never list system or internal aplication files
if(realpath($CFG['miniBrowser']['minibrowserBaseDir'])>realpath($CFG['miniBrowser']['minibrowserBaseDir'].$R['path'])){
	$R['path']=""; // should a "hack-warning" be generated?
}
$baseDir=$CFG['miniBrowser']['minibrowserBaseDir'].$R['path'];

$dirContents=scanDirectories($baseDir);

$smarty->assign('targetInput',$R['targetInput']);
$smarty->assign('filter',$R['filter']);
$smarty->assign('pathElements',explodeClean('/',$R['path']));
$smarty->assign('target',$R['target']);
$smarty->assign('dirContents',$dirContents);
$smarty->assign('path',$R['path']);
$smarty->display('AJAXBrowser.tpl');
