<?php if(!defined('master_script')) die();

/**
 * File browser
 *
 * @category   Extensions (files)
 * @author     Nico Wenig
 * @version	   2010-02-15
 */

?>

<!-- EXTENSION: files -->

<?php quick_help(txt('files', 'Neben den üblichen Funktionen zum Verwalten von Dateien, können Sie über „Eigenschaften” für eine beliebige Datei  Titel und Beschreibung verfassen, welche dann zum Beispiel in Galerien für die gerade geladene Datei automatisch angezeigt werden.')); ?>

<div id="filetree-selector">
	<select class="auto-select" size="1">
		<option <?php if($_GET['pagetype'] == 'standard') echo 'selected="selected"'; ?> value="index.php?backend=files&amp;pagetype=standard"><?php echo txt('files', 'Standardseiten'); ?></option>
		<option <?php if($_GET['pagetype'] == 'news') echo 'selected="selected"'; ?>  value="index.php?backend=files&amp;pagetype=news"><?php echo txt('files', 'Nachrichtenseiten'); ?></option>
		<?php connector('files select pagetypes'); ?>
	</select>

	<select class="auto-select" size="1">
		<option value=""><?php echo $catalogue_label; ?> …</option>
		<?php foreach($catalogue_list as $catalogue_entry) { ?>
			<option value="index.php?backend=files&amp;pagetype=<?php echo $_GET['pagetype']; ?>&amp;catalogue=<?php echo $catalogue_entry->id; ?>" <?php if(isset($_GET['catalogue']) && $_GET['catalogue'] == $catalogue_entry->id) echo 'selected="selected"'; ?>><?php echo $catalogue_entry->title; ?></option>
		<?php } ?>
	</select>
	
	<select id="files-pages" size="1">
		<option value=""><?php echo txt('files', 'Seite'); ?> …</option>
		<?php foreach($pages_list as $page_entry) { ?>
			<option value="<?php echo $page_entry->alias; ?>" <?php if(isset($_GET['page']) && $_GET['page'] == $page_entry->alias) echo 'selected="selected"'; ?>><?php echo $page_entry->title; ?></option>
			<?php $last = $page_entry->alias; ?>
		<?php } ?>
	</select>
</div>

<div id="file-options">
	<span class="separator"><?php echo txt('files', 'Bearbeiten'); ?> ▸</span>
	<a onclick="filetreeRename()" title="<?php echo txt('files', 'Umbenennen'); ?>"><img src="<?php echo $system_data['folder']['plugins']; ?>icons/pencil.png"></a>
	<a id="files-edit" onclick="filetreeEdit(); return false" title="<?php echo txt('files', 'Eigenschaften'); ?> (<?php echo txt('files', 'ALT / CTRL + E'); ?>)"><img src="<?php echo $system_data['folder']['plugins']; ?>icons/page_white_edit.png"></a>
	<?php if($_SESSION['user'] == sha1($administrator_name)) { ?><a onclick="filetreeDelete()" title="<?php echo txt('files', 'Löschen'); ?> (<?php echo txt('files', 'ALT / CTRL + D'); ?>)"><img src="<?php echo $system_data['folder']['plugins']; ?>icons/delete.png"></a><?php } ?>
	<span class="separator"><?php echo txt('files', 'Transfer'); ?> ▸</span>
	<a onclick="filetreeDownload()" title="<?php echo txt('files', 'Herunterladen'); ?> (<?php echo txt('files', 'ALT / CTRL + O'); ?>)"><img src="<?php echo $system_data['folder']['plugins']; ?>icons/arrow_down.png"></a>
	<a onclick="filetreeUpload(true)" title="<?php echo txt('files', 'Hochladen'); ?>"><img src="<?php echo $system_data['folder']['plugins']; ?>icons/arrow_up.png"></a>
	<span class="separator"><?php echo txt('files', 'Neu'); ?> ▸</span>
	<a onclick="filetreeNewFolder(true)" title="<?php echo txt('files', 'Neu'); ?>"><img src="<?php echo $system_data['folder']['plugins']; ?>icons/folder.png"></a>
</div>

<div id="filetree-new" style="display: none">
	<p>
		<input style="display: inline; width: 75%" type="text" id="filetree-new-input" value=""> 
		<input type="button" onclick="filetreeNewFolder.create()" value="<?php echo txt('files', 'Speichern'); ?>">
	</p>
</div>

<div id="filetree-upload" style="display: none">
	<iframe name="filetreeUploadIframe" id="filetreeUploadIframe" src="about:blank" style="display: none"></iframe>
	<form name="filetree-upload-form" id="filetree-upload-form" enctype="multipart/form-data" action="index.php?backend&amp;actions=filebrowser.php&amp;action=upload&amp;path=pages" method="post" target="filetreeUploadIframe">
		<p><input type="file" name="file"> <input type="submit" value="<?php echo txt('files', 'Transfer starten'); ?>" onclick="document.getElementById('filetree-upload-status').style.visibility = 'visible'"> <img id="filetree-upload-status" style="visibility: hidden; margin: 0 0 -5px 5px" src="<?php echo $system_data['folder']['backend']; ?>mask/symbols/loading.gif" alt="Loading ‚Ä¶"></p>
		<p><input type="checkbox" checked="checked" name="unzip" id="unzip"> <label class="checkbox" for="unzip"><?php echo txt('files', 'ZIP automatisch entpacken'); ?></label></p>
		<input type="hidden" name="dirpath" id="filetree-upload-dirpath" value="pages/">
	</form>
</div>

<div id="filetree-rename" style="display: none">
	<p>
		<input style="display: inline; width: 75%" type="text" id="filetree-rename-input" value=""> 
		<input type="button" onclick="filetreeRename.rename()" id="filetree-rename-button" value="<?php echo txt('files', 'Umbenennen'); ?>">
	</p>
</div>

<div>
	<input id="filetree-path" type="text" value="…" onclick="this.select()">
</div>

<div id="filetree" class="dir open">
</div>

<script type="text/javascript">
	var pagePath = '';
	
	var filetreeLoadPage = function(page) {
		pagePath = 'pages/' + page + '/';
		document.getElementById('filetree').innerHTML = '<ul><li id="filetree-page-folder" class="dir closed"><a class="dir" id="root-dir" onclick="MoreCSS.filetree.loadNextFiletree(this.parentNode)" rel="pages/' + page + '/">' + page + '</a></li></ul>';
		document.getElementById('filetree').className = 'dir closed';
		MoreCSS.filetree(document.getElementById('filetree'), ['filetree: pages/' + page, 'filetree-server: index.php?backend&actions=morecss-filelist.php&path=', 'filetree-callback: showFiletreeElement']);
		MoreCSS.filetree.loadNextFiletree(document.getElementById('root-dir').parentNode);
	};

	<?php if(isset($_GET['page']) && $_GET['page'] != '' && is_dir($system_data['folder']['pages'] . $_GET['page'])) { ?>
		filetreeLoadPage('<?php echo $_GET['page']; ?>');
	<?php } ?>
		
	var selectedItem = {};
	var imageExtensions = { 'jpg' : 1, 'jpeg' : 1, 'png' : 1, 'gif' : 1, 'bmp' : 1 };

	// Filetree callback
	var showFiletreeElement = function(type, element) {
		if(selectedItem['element']) selectedItem['element'].firstChild.style.fontWeight = 'normal';
		element.firstChild.style.fontWeight = 'bold';
		
		selectedItem['element'] = element;
		selectedItem['type'] = type;
		selectedItem['path'] = addslashes(element.firstChild.rel);
		selectedItem['dirpath'] = selectedItem['path'];
		selectedItem['basepath'] = selectedItem['path'];
		selectedItem['basename'] = selectedItem['path'];

		filetreePathinfo();

		// Parse dirpath
		selectedItem['dirpath'] = selectedItem['dirpath'].substring(0, selectedItem['dirpath'].lastIndexOf('/') + 1);

		// Parse basepath
		if(selectedItem['basepath'].lastIndexOf('/') + 1 == selectedItem['basepath'].length)
			selectedItem['basepath'] = selectedItem['basepath'].substring(0, selectedItem['basepath'].lastIndexOf('/'));
		selectedItem['basepath'] = selectedItem['basepath'].substring(0, selectedItem['basepath'].lastIndexOf('/') + 1);
		
		// Parse basename
		if(selectedItem['basename'].lastIndexOf('/') + 1 == selectedItem['basename'].length)
			selectedItem['basename'] = selectedItem['basename'].substring(0, selectedItem['basename'].lastIndexOf('/'));
		selectedItem['basename'] = selectedItem['basename'].substring(selectedItem['basename'].lastIndexOf('/') + 1);		
		
		// Paste item data
		document.getElementById('filetree-path').value = stripslashes(element.firstChild.rel);
		document.getElementById('filetree-rename-input').value = selectedItem['basename'];
		document.getElementById('filetree-upload-dirpath').value = selectedItem['dirpath'];
		
		onFiletreeInit();
	};
	
	// On filetree init
	var onFiletreeInit = function() {
		// Add tooltip to all image links
		var thumbnailSize = 250;
		var links = document.getElementById('filetree').getElementsByTagName('A');
		for(var i = 0; i < links.length; i++)
			if(imageExtensions[links[i].className])
				MoreCSS.tooltip(links[i], ['tooltip-class:filetree-preview'], '<img src="<?php echo $system_data['folder']['plugins']; ?>thumbnail/thumbnail.php?image=' + links[i].rel + '&thumbnail_crop=0&thumbnail_save=0">');
		
		// Disable rename button if folder is a page folder
		document.getElementById('filetree-rename-button').disabled = (selectedItem['path'] == pagePath) ? true : false;
	};
	
	// Get pathinfo for item
	var filetreePathinfo = function() {
		var action = MoreCSS.createXMLHttpRequest();
	   	action.open('get', 'index.php?backend&actions=filebrowser.php&action=pathinfo&path=' + selectedItem['path'], true);
	   	
	    action.onreadystatechange = function() {
	    	if(action.readyState == 4 && action.status == 200)
	    		selectedItem['element'].title = action.responseText;
	    };

	    action.send(null);
	};
	
	// Hide all other options
	var hideAllOptions = function(activeOption) {
		if(activeOption != 'filetree-upload') MoreCSS.rollIn(document.getElementById('filetree-upload'), ['roll-in:fast']);
		if(activeOption != 'filetree-new') MoreCSS.rollIn(document.getElementById('filetree-new'), ['roll-in:fast']);
		if(activeOption != 'filetree-rename') MoreCSS.rollIn(document.getElementById('filetree-rename'), ['roll-in:fast']);
	};
	
	// Reload part of Filetree
	var filetreeReload = function() {
		var element = (selectedItem['type'] == 'dir') ? selectedItem['element'] : selectedItem['element'].parentNode.parentNode;
		var rel = (selectedItem['type'] == 'dir') ? selectedItem['path'] : element.firstChild.rel;
		var basename = (selectedItem['type'] == 'dir') ? selectedItem['element'].firstChild.innerHTML : element.firstChild.innerHTML;
		
		element.innerHTML = '<a class="dir" rel="' + rel + '" onclick="MoreCSS.filetree.loadNextFiletree(this.parentNode)">' + basename + '</a>';
		MoreCSS.filetree(element, ['filetree:' + selectedItem['dirpath'], 'filetree-server:index.php?backend&actions=morecss-filelist.php&path=', 'filetree-callback:showFiletreeElement'], true);
	};
	
	// Delete open image tooltip if file is deleted
	var filetree_deleteTooltips = function(element) {
		var elements = document.getElementsByTagName('body')[0].getElementsByTagName('div');
		
		for(var i = 0; i < elements.length; i++) {
			if(elements[i].className == 'filetree-preview' && elements[i].style.visibility == 'visible') {
				elements[i].parentNode.removeChild(elements[i]);
				break;
			}
		}
	};
	
	// Download item
	var filetreeDownload = function() {
		if(selectedItem['type'] == 'file')
			window.open(selectedItem['path']);
	};

	// Upload item
	var filetreeUpload = function(showForm) {
		hideAllOptions('filetree-upload');
		if(!selectedItem['element']) return false;

		if(showForm) {
			MoreCSS.rollAuto(document.getElementById('filetree-upload'), ['roll-auto:fast']);
		} else {
			document.getElementById('filetree-upload-status').style.visibility = 'hidden';
	
			var result = window.frames.filetreeUploadIframe.document.getElementById('message');
			
			if(result) {
				if(result.innerHTML != 0 && result.innerHTML != 1) alert(result.innerHTML);
				if(result.innerHTML == 0) alert('<?php echo txt('files', 'Es ist ein unbekannter Fehler aufgetreten.'); ?>');
				if(result.innerHTML == 1) filetreeReload();
			} else
				alert('<?php echo txt('files', 'Es ist ein unbekannter Fehler aufgetreten.'); ?>');
		}
	};
	
	// New folder
	var filetreeNewFolder = function() {
		hideAllOptions('filetree-new');
		if(!selectedItem['element']) return false;
		
		MoreCSS.rollAuto(document.getElementById('filetree-new'), ['roll-auto:fast']);
		
		filetreeNewFolder.create = function() {
			var newDirName = document.getElementById('filetree-new-input').value;
			if(newDirName == '') return false;
			
			if(!newDirName.match(/^[\w\-]+$/)) {
					alert('<?php echo txt('files', 'Verwenden Sie in Verzeichnis- und Dateinamen ausschließlich Buchstaben von a bis z oder den Binde- und Unterstrich.'); ?>');
				return false;
			} 
			
			if(newDirName != '') {
				MoreCSS.opacity(selectedItem['element'], null, '0.5');
    			
    			var action = MoreCSS.createXMLHttpRequest();
    		   	action.open('get', 'index.php?backend&actions=filebrowser.php&action=newdir&path=' + selectedItem['dirpath'] + '&dirname=' + newDirName, true);
    		   	
    		    action.onreadystatechange = function() {
    		    	if(action.readyState == 4 && action.status == 200) {
    		    		if(action.responseText != '') alert(action.responseText);
    	    			MoreCSS.opacity(selectedItem['element'], null, 1);
    	    			filetreeReload();
    		    	}
    		    };
    	
    		    action.send(null);
			}
		}
	};

	// Rename item
	var filetreeRename = function() {
		hideAllOptions('filetree-rename');
		if(!selectedItem['element']) return false;
	
		MoreCSS.rollAuto(document.getElementById('filetree-rename'), ['roll-auto:fast']);
		
		filetreeRename.rename = function() {
    		var newname = document.getElementById('filetree-rename-input').value;
    		if(newname == '' || !selectedItem['basepath']) return false;
    		
    		var check = (selectedItem['type'] == 'file') ? newname.match(/^[\w\-.]+$/) : newname.match(/^[\w\-]+$/);
    		
    		if(!check) {
    			alert('<?php echo txt('files', 'Verwenden Sie in Verzeichnis- und Dateinamen ausschließlich Buchstaben von a bis z oder den Binde- und Unterstrich.'); ?>');
    			return false;
    		}
    		
    		MoreCSS.opacity(selectedItem['element'], null, '0.5');
    		
    		var action = MoreCSS.createXMLHttpRequest();
    	   	action.open('get', 'index.php?backend&actions=filebrowser.php&action=rename&path=' + selectedItem['basepath'] + '&oldname=' + selectedItem['basename'] + '&newname=' + newname + (selectedItem['type'] == 'dir' ? '/' : ''), true);
    	   	
    	    action.onreadystatechange = function() {
    	    	if(action.readyState == 4 && action.status == 200) {
        			MoreCSS.opacity(selectedItem['element'], null, 1);

    	    		if(action.responseText == '') {
    	    			selectedItem['element'].firstChild.innerHTML = newname;
    	    			selectedItem['element'].firstChild.rel = selectedItem['basepath'] + newname + (selectedItem['type'] == 'dir' ? '/' : '');
    	    			showFiletreeElement(selectedItem['type'], selectedItem['element']);
    	    			if(selectedItem['type'] == 'dir') filetreeReload();
    	    		} else {
    	    			alert(action.responseText);
    	    		}
    	    	}
    	    };
    
		    action.send(null);
		};
	};

	// Edit item
	var filetreeEdit = function(link) {
		if(selectedItem['element'] && selectedItem['type'] == 'file') {
			hideAllOptions('');
			var link = document.getElementById('files-edit');
			link.href = 'index.php?backend&actions=fileeditor.php&type=image&path=' + selectedItem['path'];
			MoreCSS.modalWindow(link, ['modal-window-width:670', 'modal-window-height:480'], 'iframe');
		}
	};
	
	// Delete item
	var filetreeDelete = function() {
		if(selectedItem['path'] == pagePath) return false;
		
		if(selectedItem['element']) {
			var question = selectedItem['type'] == 'dir' ? '<?php echo txt('files', 'Wollen Sie das Verzeichnis wirklich löschen?'); ?>' : '<?php echo txt('files', 'Wollen Sie die Datei wirklich löschen?'); ?>';
			if(confirm(question) == true) {
				MoreCSS.opacity(selectedItem['element'], null, '0.5');
				
				var action = MoreCSS.createXMLHttpRequest();
			   	action.open('get', 'index.php?backend&actions=filebrowser.php&action=delete&path=' + selectedItem['basepath'] + '&name=' + selectedItem['basename'], true);
			   	
			    action.onreadystatechange = function() {
			    	if(action.readyState == 4 && action.status == 200) {
		    			MoreCSS.opacity(selectedItem['element'], null, 1);
		    			
			    		if(action.responseText == '') {
			    			selectedItem['element'].style.display = 'none';
			    			showFiletreeElement('dir', selectedItem['element'].parentNode.parentNode.getElementsByTagName('A')[0].parentNode);
			    			filetree_deleteTooltips(selectedItem['element']);
			    		} else
			    			alert(action.responseText);
			    	}
			    };
		
			    action.send(null);
			}
		}
	};
	
	// Key events
	var files_getKeyCode = function(event) {
		event = event || window.event;
		var key = event.keyCode;
		
		if(key == 79 && (event.ctrlKey == true || event.altKey == true)) filetreeDownload();
		if(key == 69 && (event.ctrlKey == true || event.altKey == true)) filetreeEdit();
		if(key == 68 && (event.ctrlKey == true || event.altKey == true)) filetreeDelete();
	}
	
	window.onkeydown = files_getKeyCode;
</script>