<?php
include('settings.php');

$sMsg = '';
$locale = !empty($_REQUEST['lang']) ? $_REQUEST['lang'] : Config::read('locale');

/*** Permission ***/
$bReadOnly0 = false;
$bReadOnly1 = false;
$bReadOnly2 = false;
$bReadOnly3 = false;
/*** /Permission ***/

$currFolder = Config::read('sources');
$currFolder = reset($currFolder);
$currFolder = $currFolder['base'];
$ffilter = '';
$sUploadedFile = '';

# FILE UPLOADED #
if (isset($_FILES['File1'])) {
	if (isset($_POST['inpCurrFolder2'])) {
		$currFolder = $_POST['inpCurrFolder2'];
	}
	if (isset($_REQUEST['inpFilter'])) {
		$ffilter = $_REQUEST['inpFilter'];
	}

	# Max filesize #
	if (Config::read('maxFileSize') && ($_FILES['File1']['size'] > Config::read('maxFileSize'))) {
		$sMsg = 'The file exceeds the maximum size allowed.';

		# Allowed extensions #
	} else if (!Config::allowed($_FILES['File1']['name'])) {
		$sMsg = 'The File Type is not allowed.';

		# Error moving file
	} else if (!move_uploaded_file($_FILES['File1']['tmp_name'], $currFolder . "/" . basename($_FILES['File1']['name']))) {
		$sMsg = 'Upload failed.';

		# Success #
	} else {
		$sMsg = '';
		$sUploadedFile = $_FILES['File1']['name'];
		@chmod($currFolder . '/' . basename($_FILES['File1']['name']), 0644);
	}
} else {
	if (isset($_POST['inpCurrFolder'])) {
		$currFolder = $_POST['inpCurrFolder'];
	}
	if (isset($_REQUEST['ffilter'])) {
		$ffilter = $_REQUEST['ffilter'];
	}
}

# FILE DELETED #
if (isset($_POST['inpFileToDelete'])) {
	$filename = pathinfo($_POST['inpFileToDelete']);
	$filename = $filename['basename'];
	if (!empty($filename)) {
		unlink($currFolder . "/" . $filename);
	}
	$sMsg = '';
}

/*** Permission *** /
 * $bWriteFolderAdmin=false;
 * if($sBase0!="")
 * {
 * if(strtolower($currFolder)!=str_replace(strtolower($sBase0),"",strtolower($currFolder)) AND
 * $bReadOnly0==true) $bWriteFolderAdmin=true;
 * }
 * if($sBase1!="")
 * {
 * if(strtolower($currFolder)!=str_replace(strtolower($sBase1),"",strtolower($currFolder)) AND
 * $bReadOnly1==true) $bWriteFolderAdmin=true;
 * }
 * if($sBase2!="")
 * {
 * if(strtolower($currFolder)!=str_replace(strtolower($sBase2),"",strtolower($currFolder)) AND
 * $bReadOnly2==true) $bWriteFolderAdmin=true;
 * }
 * if($sBase3!="")
 * {
 * if(strtolower($currFolder)!=str_replace(strtolower($sBase3),"",strtolower($currFolder)) AND
 * $bReadOnly3==true) $bWriteFolderAdmin=true;
 * }
 * $sFolderAdmin="";
 * if($bWriteFolderAdmin)$sFolderAdmin="style='display:none'";
 * /*** /Permission ***/

function writeFolderSelections() {
	global $currFolder;

	foreach (Config::read('sources') as $source) {
		$options = recursive($source['base'], $source['base'], $source['name']);
	}

	$select = '<select name="selCurrFolder" id="selCurrFolder" onchange="changeFolder()" class="inpSel">';
	$select .= implode("\n", $options);
	$select .= '</select>';
	return $select;
}

function recursive($path, $pathBase, $name) {
	global $currFolder;
	$options = [];

	$bases = [];
	foreach (Config::read('sources') as $source) {
		$bases[] = $source['base'];
	}

	# Write base folder #
	if (in_array($path, $bases)) {
		$selected = $currFolder == $path ? ' selected="selected"' : '';
		$options[] = "<option value=\"{$path}\"{$selected}>" . (!empty($name) ? $name : '/') . "</option>";
	}

	# Read all files from dir #
	$files = [];
	$dir = opendir($path);
	while ($file = readdir($dir))
		if (isset($file{0}) && $file{0} != '.') {
			$files[] = $file;
		}
	closedir($dir);
	sort($files);

	# Write all subdirs found in current dir #
	foreach ($files as $file) {
		if (is_dir($file = "{$path}/{$file}")) {
			$selected = $currFolder == $file ? ' selected="selected"' : '';
			$display = $name . str_replace($bases, null, $file);
			$options[] = "<option value=\"{$file}\"{$selected}>{$display}</option>";

			$options += recursive($file, $path, $name);
		}
	}
	return $options;
}

function getExt($filename) {
	if (!strpos($filename, '.')) {
		return null;
	}
	$split = explode('.', $filename);
	return strtolower(end($split));
}

function writeFileSelections() {
	global $sFolderAdmin;
	global $ffilter;
	global $sUploadedFile;
	global $currFolder;
	global $bWriteFolderAdmin;

	$empty = true;
	$nIndex = 0;
	$iSelected = '';
	$backround = '#e7e7e7';

	echo '<div style="overflow:auto;height:277px;width:100%;margin-top:3px;margin-bottom:2px;">';
	echo '<table border="0" cellpadding="2" cellspacing="0" width="100%" height="100%">';

	# Read all files from dir #
	$files = [];
	$dir = opendir($currFolder);
	while ($file = readdir($dir))
		if (isset($file{0}) && $file{0} != '.') {
			$files[] = $file;
		}
	closedir($dir);
	sort($files);

	foreach ($files as $filename) {
		$file = "{$currFolder}/{$filename}";

		if (!is_dir($file)) {

			$ext = getExt($file);
			$empty = false;

			# Filter menu #
			$filters = Config::read('filters');
			if (!isset($filters[$ffilter]) || in_array($ext, $filters[$ffilter])) {
				$nIndex = $nIndex + 1;
				$bFileFound = true;

				# Needed to make relative paths #
				$bases = [];
				foreach (Config::read('sources') as $source) {
					$bases[] = $source['base'];
				}

				# Coloring alt rows #
				$backround = $backround == '#e7e7e7' ? '' : '#e7e7e7';
				$sTmp1 = strtolower($file);
				$sTmp2 = strtolower($sUploadedFile);
				if ($sTmp1 == $sTmp2) {
					$backround = 'yellow';
					$iSelected = $nIndex;
				}

				?>
				<tr style="background:<?= $backround ?>">
					<td><img src="images/<?= Config::icon($ext) ?>" /></td>
					<td valign="top" width="100%">
						<div style="width:220px;overflow:hidden;white-space:nowrap">
							<u id="idFile<?= $nIndex ?>" style="cursor:pointer" onclick="selectFile(<?= $nIndex ?>)"><?= $filename ?></u>
						</div>
					</td>
					<td>
						<img style="cursor:pointer" onclick="downloadFile(<?= $nIndex ?>)" src="download.gif"><input type="hidden" name="inpFile<?= $nIndex ?>" id="inpFile<?= $nIndex ?>" value="<?= str_replace($bases, null, $file) ?>">
					</td>
					<td valign="top" align="right" nowrap="nowrap"><?= round(filesize($file) / 1024, 1) ?>
						kb&nbsp;
					</td>
					<td valign="top" nowrap="nowrap" onclick="deleteFile(<?= $nIndex ?>)">
						<u style="font-size:10px;cursor:pointer;color:crimson" <?= $sFolderAdmin ?>>
							<script>document.write(getTxt('del'))</script>
						</u></td>
				</tr>
				<?php
			}
		}
	}

	$empty = $empty ? ' align=center><script>document.write(getTxt("Empty..."))</script>' : '>';
	echo "<tr><td colspan=\"4\" height=\"100%\"{$empty}</td></tr></table></div>";
	echo '<input type="hidden" name="inpUploadedFile" id="inpUploadedFile" value="' . $iSelected . '">';
	echo '<input type="hidden" name="inpNumOfFiles" id="inpNumOfFiles" value="' . $nIndex . '">';
}

?>
<html>
<head>
	<title>Asset Manager</title>
	<meta http-equiv="Content-Type" content="text-html; charset=UTF-8">
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Expires" content="-1">
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src='language/<?= $locale ?>/asset.js'></script>
	<script type="text/javascript">
		writeTitle();
		var bReturnAbsolute =<?= Config::read('absolutePaths') ? 'true' : 'false' ?>;
		var activeModalWin;

		function getAction() {
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			//Clean previous ffilter=...
			sQueryString = window.location.search.substring(1);
			sQueryString = sQueryString.replace(/ffilter=media/, "");
			sQueryString = sQueryString.replace(/ffilter=image/, "");
			sQueryString = sQueryString.replace(/ffilter=flash/, "");
			sQueryString = sQueryString.replace(/ffilter=/, "");
			if (sQueryString.substring(sQueryString.length - 1) == "&")
				sQueryString = sQueryString.substring(0, sQueryString.length - 1);

			if (sQueryString.indexOf("=") == -1) {//no querystring
				sAction = "assetmanager.php?ffilter=" + document.getElementById("selFilter").value;
			}
			else {
				sAction = "assetmanager.php?" + sQueryString + "&ffilter=" + document.getElementById("selFilter").value
			}
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			return sAction;
		}

		function applyFilter()//ffilter
		{
			var Form1 = document.forms.Form1;

			Form1.elements.inpCurrFolder.value = document.getElementById("selCurrFolder").value;
			Form1.elements.inpFileToDelete.value = "";

			Form1.action = getAction();
			Form1.submit()
		}

		function refreshAfterDelete(sDestination) {
			var Form1 = document.forms.Form1;

			Form1.elements.inpCurrFolder.value = sDestination;
			Form1.elements.inpFileToDelete.value = "";

			Form1.action = getAction();
			Form1.submit();
		}

		function changeFolder() {
			var Form1 = document.forms.Form1;

			Form1.elements.inpCurrFolder.value = document.getElementById("selCurrFolder").value;
			Form1.elements.inpFileToDelete.value = "";

			Form1.action = getAction();
			Form1.submit();
		}

		function upload() {
			var Form2 = document.forms.Form2;

			if (Form2.elements.File1.value == "") return;

			var sFile = Form2.elements.File1.value.substring(Form2.elements.File1.value.lastIndexOf("\\") + 1);
			for (var i = 0; i < document.getElementById("inpNumOfFiles").value; i++) {
				/*if(sFile==document.getElementById("idFile"+(i*1+1)).innerHTML)
				  {
				  if(confirm(getTxt("File already exists. Do you want to replace it?"))!=true)return;
				  }*/
			}

			Form2.elements.inpCurrFolder2.value = document.getElementById("selCurrFolder").value;
			document.getElementById("idUploadStatus").innerHTML = getTxt("Uploading...");

			Form2.action = getAction();
			Form2.submit();
		}

		function newFolder() {

			var currentPath = window.location.href;
			currentPath = currentPath.substring(0, currentPath.lastIndexOf("/"));
			parent.modalDialogShow(currentPath + "/foldernew.php", 250, 170, window);
		}

		function deleteFolder() {
			var selCurrFolder = document.getElementById("selCurrFolder");

			if (selCurrFolder.value.toLowerCase() == document.getElementById("inpAssetBaseFolder0").value.toLowerCase() ||
				selCurrFolder.value.toLowerCase() == document.getElementById("inpAssetBaseFolder1").value.toLowerCase() ||
				selCurrFolder.value.toLowerCase() == document.getElementById("inpAssetBaseFolder2").value.toLowerCase() ||
				selCurrFolder.value.toLowerCase() == document.getElementById("inpAssetBaseFolder3").value.toLowerCase()) {
				alert(getTxt("Cannot delete Asset Base Folder."));
				return;
			}

			var currentPath = window.location.href;
			currentPath = currentPath.substring(0, currentPath.lastIndexOf("/"));
			parent.modalDialogShow(currentPath + "/folderdel.php", 250, 170, window);

		}

		function downloadFile(index) {
			sFile_RelativePath = document.getElementById("inpFile" + index).value;
			window.open(sFile_RelativePath)
		}

		function selectFile(index) {
			sFile_RelativePath = document.getElementById("inpFile" + index).value;

			//This will make an Absolute Path
			if (bReturnAbsolute) {
				sFile_RelativePath = window.location.protocol + "//" + window.location.host.replace(/:80/, "") + sFile_RelativePath
				//Ini input dr yg pernah pake port:
				//sFile_RelativePath = window.location.protocol + "//" + window.location.host.replace(/:80/,"") + "/" + sFile_RelativePath.replace(/\.\.\//g,"")
			}

			document.getElementById("inpSource").value = '<?php echo Config::read('backstep') ?>' + encodeURI(sFile_RelativePath);

			var arrTmp = sFile_RelativePath.split(".");
			var sFile_Extension = arrTmp[arrTmp.length - 1];
			var sHTML = "";

			//Image
			if (sFile_Extension.toUpperCase() == "GIF" || sFile_Extension.toUpperCase() == "JPG" || sFile_Extension.toUpperCase() == "PNG") {
				sHTML = "<img src=\"<?php echo Config::read('backstep') ?>" + sFile_RelativePath + "\" >"
			}
			//SWF
			else if (sFile_Extension.toUpperCase() == "SWF") {
				sHTML = "<object " +
					"classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' " +
					"width='100%' " +
					"height='100%' " +
					"codebase='http://active.macromedia.com/flash6/cabs/swflash.cab#version=6.0.0.0'>" +
					" <param name=movie value='<?php echo Config::read('backstep') ?>" + sFile_RelativePath + "'>" +
					" <param name=quality value='high'>" +
					" <embed src='<?php echo Config::read('backstep') ?>" + sFile_RelativePath + "' " +
					"	  width='100%' " +
					"	  height='100%' " +
					"	  quality='high' " +
					"	  pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'>" +
					" </embed>" +
					"</object>";
			}
			//Video
			else if (sFile_Extension.toUpperCase() == "WMV" || sFile_Extension.toUpperCase() == "AVI" || sFile_Extension.toUpperCase() == "MPG") {
				sHTML = "<embed src='<?php echo Config::read('backstep') ?>" + sFile_RelativePath + "' hidden=false autostart='true' type='video/avi' loop='true'></embed>";
			}
			//Sound
			else if (sFile_Extension.toUpperCase() == "WMA" || sFile_Extension.toUpperCase() == "WAV" || sFile_Extension.toUpperCase() == "MID") {
				sHTML = "<embed src='<?php echo Config::read('backstep') ?>" + sFile_RelativePath + "' hidden=false autostart='true' type='audio/wav' loop='true'></embed>";
			}
			//Files (Hyperlinks)
			else {
				sHTML = "<br><br><br><br><br><br>Not Available"
			}

			document.getElementById("idPreview").innerHTML = sHTML;
		}

		function deleteFile(index) {
			if (confirm(getTxt("Delete this file ?")) == true) {
				sFile_RelativePath = document.getElementById("inpFile" + index).value;

				var Form1 = document.getElementById("Form1");
				Form1.elements.inpCurrFolder.value = document.getElementById("selCurrFolder").value;
				Form1.elements.inpFileToDelete.value = sFile_RelativePath;

				Form1.action = getAction();
				Form1.submit();
			}
		}

		bOk = false;

		function doOk() {
			(opener ? opener : openerWin).setAssetValue(document.getElementById("inpSource").value);
			bOk = true;
			self.close();
		}

		function doUnload() {
			if (navigator.appName.indexOf('Microsoft') != -1)
				if (!bOk) window.returnValue = "";
				else if (!bOk) (opener ? opener : openerWin).setAssetValue("");
		}

	</script>
</head>
<body onunload="doUnload()" onload="loadTxt();this.focus();if(document.getElementById('inpUploadedFile').value!='')selectFile(document.getElementById('inpUploadedFile').value);" style="overflow:hidden;margin:0px;">

<input type="hidden" name="inpAssetBaseFolder0" id="inpAssetBaseFolder0" value="<?php /* echo $sBase0 */ ?>">
<input type="hidden" name="inpAssetBaseFolder1" id="inpAssetBaseFolder1" value="<?php /* echo $sBase1 */ ?>">
<input type="hidden" name="inpAssetBaseFolder2" id="inpAssetBaseFolder2" value="<?php /* echo $sBase2 */ ?>">
<input type="hidden" name="inpAssetBaseFolder3" id="inpAssetBaseFolder3" value="<?php /* echo $sBase3 */ ?>">

<table width="100%" height="100%" align=center style="" cellpadding=0 cellspacing=0 border=0>
	<tr>
		<td valign=top style="height:100%;background:url('bg.gif') no-repeat right bottom;padding-top:5px;padding-left:5px;padding-right:5px;padding-bottom:0px;">
			<!--ffilter-->
			<form method=post name="Form1" id="Form1">
				<input type="hidden" name="inpFileToDelete">
				<input type="hidden" name="inpCurrFolder">
			</form>

			<table width=100% border="0">
				<tr>
					<td>
						<table cellpadding="2" cellspacing="2" border="0" width="100%">
							<tr>
								<td valign=center nowrap><?= writeFolderSelections() ?>&nbsp;</td>
								<td nowrap>
									<span onclick="newFolder()" style="cursor:pointer;"><u><span name="txtLang" id="txtLang" <?php echo !empty($sFolderAdmin) ? $sFolderAdmin : '' ?>>New&nbsp;Folder</span></u></span>&nbsp;
									<span onclick="deleteFolder()" style="cursor:pointer;"><u><span name="txtLang" id="txtLang" <?php echo !empty($sFolderAdmin) ? $sFolderAdmin : '' ?>>Del&nbsp;Folder</span></u></span>
								</td>
								<td width=100% align="right">

									<?php
									//ffilter~~~~~~~~~
									$sHTMLFilter = "<select name=selFilter id=selFilter onchange='applyFilter()' class='inpSel'>"; //ffilter
									$sAll = "";
									$sMedia = "";
									$sImage = "";
									$sFlash = "";
									if ($ffilter == "")
										$sAll = "selected";
									if ($ffilter == "media")
										$sMedia = "selected";
									if ($ffilter == "image")
										$sImage = "selected";
									if ($ffilter == "flash")
										$sFlash = "selected";
									$sHTMLFilter = $sHTMLFilter . " <option name=optLang id=optLang value='' " . $sAll . "></option>";
									$sHTMLFilter = $sHTMLFilter . " <option name=optLang id=optLang value='media' " . $sMedia . "></option>";
									$sHTMLFilter = $sHTMLFilter . " <option name=optLang id=optLang value='image' " . $sImage . "></option>";
									$sHTMLFilter = $sHTMLFilter . " <option name=optLang id=optLang value='flash' " . $sFlash . "></option>";
									$sHTMLFilter = $sHTMLFilter . "</select>";
									echo $sHTMLFilter;
									//~~~~~~~~~
									?>

								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td valign=top align="center">

						<table width=100% cellpadding=0 cellspacing=0>
							<tr>
								<td>
									<div id="idPreview" style="text-align:center;overflow:auto;width:297px;height:245px;border:#d7d7d7 5px solid;border-bottom:#d7d7d7 3px solid;background:#ffffff;margin-right:2;"></div>
									<div align=center>
										<input type="text" id="inpSource" name="inpSource" style="border:#cfcfcf 1px solid;width:295px" class="inpTxt">
									</div>
								</td>
								<td valign=top width="100%">
									<?php writeFileSelections(); ?>
								</td>
							</tr>
						</table>

					</td>
				</tr>
				<tr>
					<td>
						<div <?php echo $sFolderAdmin; ?>>
							<div style="height:12">
								<font color=red><?php echo $sMsg ?></font>
								<span style="font-weight:bold" id=idUploadStatus></span>
							</div>

							<form enctype="multipart/form-data" method="post" name="Form2" id="Form2">
								<input type="hidden" name="inpCurrFolder2" ID="inpCurrFolder2">
								<!--ffilter-->
								<input type="hidden" name="inpFilter" ID="inpFilter" value="<?php echo $ffilter ?>">
								<span name="txtLang" id="txtLang">Upload File</span>:
								<input type="file" id="File1" name="File1" class="inpTxt">&nbsp;
								<input name="btnUpload" id="btnUpload" type="button" value="upload" onclick="upload()">
							</form>
						</div>
					</td>
				</tr>
			</table>

		</td>
	</tr>
	<tr>
		<td class="dialogFooter" align="right">
			<table cellpadding=0 cellspacing=0>
				<tr>
					<td>
						<input name="btnOk" id="btnOk" type="button" value=" ok " onclick="doOk()" class="inpBtn" onmouseover="this.className='inpBtnOver';" onmouseout="this.className='inpBtnOut'">
					</td>
				</tr>
			</table>
		</td>
	</tr>
</table>

</body>
</html>
