<?php
/*
 * This file is part of the easy-CMS project.
 * easy-CMS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * easy-CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with easy-CMS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

// define the path context
chdir('..');
define('EASY_GUI_APP_DIR', '../');


include_once('config.inc.php');
include_once('classes/core/Site.class.php');

include_once('classes/system/Dir.class.php');
include_once('classes/system/File.class.php');

include_once('interface/egScript.class.php');
include_once('interface/egManager.class.php');
include_once('interface/egContainer.class.php');
include_once('interface/egMenuItem.class.php');
include_once('interface/egFrame.class.php');
include_once('interface/egToolTip.class.php');
include_once('interface/egRichText.class.php');
include_once('interface/egLink.class.php');
include_once('interface/egStatic.class.php');
include_once('interface/egEdit.class.php');
include_once('interface/egCheckBox.class.php');
include_once('interface/egRadioButton.class.php');
include_once('interface/egPressButton.class.php');
include_once('interface/egDropDownListBox.class.php');
include_once('interface/egPropertyList.class.php');
include_once('interface/egPropertySheet.class.php');
include_once('interface/egPropertyPage.class.php');
include_once('interface/egTreeNode.class.php');
include_once('interface/egTreeList.class.php');
include_once('interface/egSubWindow.class.php');


$site = &Site::getInstance();


//security check : user must be identified to browse repositories
$user = $site->getCurrentUser();
if(!$user || $user->getUserId() == USER_ID_ANONYMOUS) {
	die("access denied");
	exit();
}


$parentControlName	= $site->getSubmittedVar('parent_control_name');
$parentControlName2 = $site->getSubmittedVar('parent_control_name2');
$repositoryType 		= $site->getSubmittedVar('repository_type', DOCUMENTS_FOLDER);
$mode								= $site->getSubmittedVar('mode', '');


function &getNameFromURLPath($urlPath){
	$parts = explode(',', $urlPath);
	return $parts[count($parts)-1];
}


function &decodeURLPath($urlPath){
	return str_replace(',', '/', urldecode($urlPath));
}


function &getDirListFromURLPath($urlPath){
	if(!($dirList = explode(',', urldecode($urlPath)))) {
		return null;
	}
	return $dirList;
}


function &encodeDirList($node){
	$path = '';
	if(is_object($node)) {
		do{
	    if(strlen($path)) {
				$path = $node->getName().','.$path;
			}
			else {
			  $path = $node->getName();
			}
			$node = $node->getParentNode();
		}while(is_object($node));
	}
	return urlencode($path);
}


function createTree(&$treeList, &$parentNode, &$dir, &$treeNodesIdList, $level) {
	global $repositoryType;
	$uniqueId = 0;

	if(!is_object($dir)) return;

	$listing = $dir->getListing();

	for($i = 0; $i < count($listing); ++$i){
    $node = &$listing[$i];
	  if($node->getNodeType() == DIR_NODE) {
	    $treeNodeId = "trn_".$level."_".(++$uniqueId);
			$treeNodeName = $treeNodesIdList."_".$treeNodeId;
			$treeNode = &new egTreeNode($treeNodeId, $node->getName(), "interface/icons/folder_closed.png", "interface/icons/folder_open.png", "0", "", "setCurrentDir(\'".encodeDirList($node)."\');document.getElementById(\'sbw_1\').src=\'".$_SERVER['PHP_SELF']."?repository_type=".$repositoryType."&path=".encodeDirList($node)."&id=".$treeNodeName."&list=".$treeList->getId()."\';");
			createTree($treeList, $treeNode, $node, $treeNodeName, $level+1);
			$parentNode->addChild($treeNode);
	  }
	}
}


function createFrame(&$container, &$vars) {
	global $repositoryType;

	if(!isset($vars['path']) || !isset($vars['id']) || !isset($vars['list'])) {
	  return;
	}

	$extensionIcons = array("default"=>"interface/icons/icon_doc_unknown.png", "doc"=>"interface/icons/icon_doc_doc.png", "gif"=>"interface/icons/icon_doc_img.png", "jpeg"=>"interface/icons/icon_doc_img.png", "jpg"=>"interface/icons/icon_doc_img.png", "pdf"=>"interface/icons/icon_doc_pdf.png", "png"=>"interface/icons/icon_doc_img.png", "txt"=>"interface/icons/icon_doc_txt.png", "xls"=>"interface/icons/icon_doc_xls.png");
	$treeListId = $vars['list'];


	$parentNodeId = '';


	if($vars['id'] == 'trn_r') {
		$treeNodeListIndex = 0;
		$treeNodeUniqueId = 0;
		$parentNodeId = 'trn_r';
	}
	else {
		$list = explode('_', $vars['id']);
		$treeNodeListIndex = 0;
		$treeNodeUniqueId = $list[count($list)-2] + 1;
		$parentNodeId = $vars['id'];
	}


	$uniqueId = 0;


	$dirName = decodeURLPath($vars['path']);
	$dir = &new Dir($dirName, REPOSITORY_FOLDER);


	$listing = &$dir->getListing();


	$vPos = 10;

	for ($i = 0; $i < count($listing); ++$i){
    $node = &$listing[$i];
	  if($node->getNodeType() == DIR_NODE) {
	    $treeNodeId = "trn_".$treeNodeUniqueId."_".(++$treeNodeListIndex);
	    $linkId = "lnk_".(++$uniqueId);
			$treeNodeName = $parentNodeId."_".$treeNodeId;
			$action = "window.parent.treeList_".$treeListId.".selectItem(window.parent.document.getElementById(\'".$treeNodeName."\'), \'0\', \'\');window.location.href=\'".$_SERVER['PHP_SELF']."?repository_type=".$repositoryType."&path=".encodeDirList($node)."&id=".$treeNodeName."&list=".$treeListId."\';";

			$link = &new egLink($linkId, $node->getName(), 10, $vPos, 350, 18, $action, "interface/icons/folder_closed.png");
			$container->addObject($link);
	  }
	  else {
	    $linkId = "lnk_".(++$uniqueId);
			$extension = $node->getExtension();
			if(!isset($extensionIcons[$extension])) {
			  $extension = "default";
			}


/*
      $menu = &new egContextMenu("menu_container_".$linkId, 0, 0, 150, 350);
      $menu->addListItem(new egMenuItem("mnu_ct_".$linkId."_1", LANG_FILE_MENU_MOVE, "interface/icons/move.png", "launchFileMovingWindow(\'path=".$node->getNodeFullName()."\');"));
	    $menu->addListItem(new egMenuItem("mnu_ct_".$linkId."_2", LANG_FILE_MENU_RENAME, "interface/icons/edit.png", "launchFileRenamingWindow(\'path=".$node->getNodeFullName()."\');"));
			$menu->addListItem(new egMenuItem("mnu_ct_".$linkId."_3", LANG_FILE_MENU_REMOVE, "interface/icons/remove.png", "launchFileDeletionWindow(\'path=".$node->getNodeFullName()."\');"));
      $main = &new egContainer("eg_ctn_ct_".$linkId, 0, 0, 0, 0);
      $main->addObject($menu);
    	$container->addContainer($main);
*/


			//$link = &new egLink($linkId, $node->getName()." <a style=\"border: 0; padding: 0; margin: 0;\" onclick=\"javascript:cancelBubble(arguments[0]);\" href=\"javascript:egShowContextMenu(contextMenu_"."menu_container_".$linkId.");\"><img border=\"0\" src=\"interface/icons/properties.png\" /></a>", 10, $vPos, 600, 18, "sendResponse(\'".$node->getNodeFullName()."\')", $extensionIcons[$extension]);


			$link = &new egLink($linkId, $node->getName(), 10, $vPos, 350, 18, "sendResponse(\'".$node->getNodeFullName()."\')", $extensionIcons[$extension]);
			//$linkRadio = &new egRadiobutton($linkId, $node->getName(), 10, $vPos, 600, null, 'file_path', $node->getNodeFullName());


			$container->addObject($link);
			//$container->addObject($linkRadio);
		}
	  $vPos += 20;
	}
}


if(isset($_GET['path']) && isset($_GET['id']) && isset($_GET['list'])){
	// display the content of a directory
	$manager = &egManager::getInstance();


	$main = &new egContainer("main_ctn", 0, 0, 0, 0);


	createFrame($main, $_GET);


	$manager->addContainer($main);


	$scripts = new egScript();
	$line = "function sendResponse(file) {

	window.parent.setSelectedFile(file);
}
";
	$scripts->addLine($line);


	$manager->addScripts($scripts);


	echo $manager->getHTML();
}
else {
	// need $_GET['field'] to be set
	// display the repository tree
	$manager = &egManager::getInstance();
	$main = &new egContainer("main_ctn", 0, 0, 0, 0);


	switch($repositoryType) {
	  case IMAGES_FOLDER :
	    break;
	  case DOCUMENTS_FOLDER :
	    break;
	  default :
			$repositoryType = DOCUMENTS_FOLDER;
	    break;
	}


	$dir = &new Dir($repositoryType, REPOSITORY_FOLDER);


	$treeList = &new egTreeList("trl_1", "repository", 10, 10, 250, 350, "choice_tree");
	$treeNodeRoot = &new egTreeNode("trn_r", $repositoryType, "interface/icons/folder_closed.png", "interface/icons/folder_open.png", "0", "", "setCurrentDir(\'".encodeDirList($dir)."\');document.getElementById(\'sbw_1\').src=\'".$_SERVER['PHP_SELF']."?repository_type=".$repositoryType."&path=".encodeDirList($dir)."&id=trn_r&list=".$treeList->getId()."\';");

	createTree($treeList, $treeNodeRoot, $dir, $treeNodeRoot->getId(), 0);


	$treeList->insertRootNode($treeNodeRoot);


	$frame = &new egFrame("fra_1", "frame 1", 270, 10, 400, 350);
	$subWindow = &new egSubWindow("sbw_1", "select_file.php?path=".$repositoryType."&list=trl_1&id=trn_r&repository_type=".$repositoryType, 271, 11, 398, 348);

	if($mode == 'admin') {
  	$framePreview = &new egFrame("fra_2", "frame 2", 300, 420, 100, 99);
  	$subWindowPreview = &new egSubWindow("sbw_2", "../display_img.php", 307, 426, 98, 98);
  }
  else {
  	$framePreview = &new egFrame("fra_2", "frame 2", 130, 420, 100, 99);
  	$subWindowPreview = &new egSubWindow("sbw_2", "../display_img.php", 137, 426, 98, 98);
  }

	$lPos = 10;


	if($mode == 'admin') {
		$pressButton0 = &new egPressbutton("btn_0", LANG_FILE_MANAGER_REMOVE_DIR, $lPos, 370, 140, null, "removeDir()");
		$main->addObject($pressButton0);
		$lPos += 145;
	}
	$pressButton1 = &new egPressbutton("btn_1", LANG_FILE_MANAGER_CREATE_SUB_DIR, $lPos, 370, 140, null, "createSubDir()");
	$lPos += 145;
	$pressButton11 = &new egPressbutton("btn_11", LANG_FILE_MANAGER_MOVE_DIR, $lPos, 370, 130, null, "moveDir()");
	$lPos += 135;
	$pressButton2 = &new egPressbutton("btn_2", LANG_FILE_MANAGER_UPLOAD_FILE, $lPos, 370, 120, null, "uploadFile()");
	$lPos += 125;
	$pressButton3 = &new egPressbutton("btn_3", LANG_FILE_MANAGER_MULTIPLE_UPLOAD, $lPos, 370, 120, null, "multipleUpload()");


	$fileNameStatic = &new egStatic("fila_name_static", LANG_FILE_MENU_SELECTED." : ", 10, 395, 120, 0, true);
	$fileNameValue  = &new egStatic("file_name_value", "", 130, 395, 350, 0, false);


	if($mode == 'admin') {
		$linkMove = &new egLink("lnk_move", LANG_FILE_MENU_MOVE, 126, 420, 200, 18, "launchFileMovingWindow()", "interface/icons/move.png");
		$linkRename = &new egLink("lnk_rename", LANG_FILE_MENU_RENAME, 126, 440, 200, 18, "launchFileRenamingWindow()", "interface/icons/edit.png");
		$linkRemove = &new egLink("lnk_remove", LANG_FILE_MENU_REMOVE, 126, 460, 200, 18, "launchFileDeletionWindow()", "interface/icons/remove.png");
		$main->addObject($linkMove);
		$main->addObject($linkRename);
		$main->addObject($linkRemove);
	}
	else {
    $buttonPosY = 405;
    if($repositoryType == IMAGES_FOLDER) {
      $buttonPosY = 505;
    }
		$okButton = &new egPressbutton("btn_ok", "Ok", 505, $buttonPosY, 80, null, "clickOKButton();");
		$cancelButton = &new egPressbutton("btn_cancel", "Cancel", 595, $buttonPosY, 80, null, "clickCancelButton();");
		$main->addObject($okButton);
		$main->addObject($cancelButton);
	}

	if($repositoryType == IMAGES_FOLDER) {
		$main->addObject($framePreview);
		$main->addObject($subWindowPreview);
	}


	$main->addObject($pressButton1);
  $main->addObject($pressButton11);
	$main->addObject($pressButton2);
	$main->addObject($pressButton3);


	$main->addObject($fileNameStatic);
	$main->addObject($fileNameValue);


	$main->addObject($treeList);
	$main->addObject($frame);
	$main->addObject($subWindow);


	$manager->addContainer($main);




	$txtObjName  = &new egStatic("st_obname", "", 10, 5, 200, 0, true);
	$main->addObject($txtObjName);


	$scripts = new egScript();


	// hack for FCKEditor integration
	$filePrefix = '';
	$updateCommand = '';
	if($parentControlName == 'txtUrl') {
		$scriptPath = str_replace('admin', '', $site->getScriptPath());
		$location = "http://".$site->getHostName();
		if(strlen($scriptPath)) {
			$location .= "/".$scriptPath;
		}
		$filePrefix = $location."/";
		$updateCommand = "window.opener.UpdatePreview();";
	}




	$line = "
function clickOKButton() {
		sendResponse();
}
var selectedFile = '';
var currentDir = '".$repositoryType."';
function clickCancelButton() {
	window.close();
}
function launchFileMovingWindow() {
	var vars = 'path='+ selectedFile;
  document.getElementById('sbw_1').contentWindow.openWindow('move_file.php?'+'mode=ask_move_file&repository_type=".$repositoryType."&'+vars,360, 150, 0, 0);
}
function launchFileRenamingWindow() {
	var vars = 'path='+ selectedFile;
  document.getElementById('sbw_1').contentWindow.openWindow('rename_file.php?'+'mode=ask_rename_file&'+vars,330, 150, 0, 0);
}
function launchFileDeletionWindow() {
	var vars = 'path='+ selectedFile;
  document.getElementById('sbw_1').contentWindow.openWindow('delete_node.php?'+'mode=ask_delete_file&'+vars,330, 150, 0, 0);
}
function launchDirDeletionWindow() {
	var vars = 'path='+ '".REPOSITORY_FOLDER."/' + currentDir;
  openWindow('delete_node.php?'+'mode=ask_delete_dir&'+vars,330, 150, 0, 0);
}
function launchCreateNodeWindow(vars) {
  document.getElementById('sbw_1').contentWindow.openWindow('create_node.php?'+'mode=ask_create_node&'+vars,330, 150, 0, 0);
}
function launchDirMovingWindow() {
	var repositoryType = '".$repositoryType."';
  var name = currentDir;
	vars = 'type='+ repositoryType +'&name='+currentDir;
  openWindow('move_directory.php?'+vars,425, 160, 0, 0);
}
function setSelectedFile(file) {
	selectedFile = file;
	document.getElementById('file_name_value').innerHTML = file;

	if(document.getElementById('sbw_2') != null) {
		document.getElementById('sbw_2').src = '../display_img.php?prefix=preview&filename=' + file + '&max_width=90&max_height=90';
	}
}
function setCurrentDir(dir) {
	currentDir = dir;
}
function sendResponse() {
	var parentControlName2 = '".$parentControlName2."';

	window.opener.document.getElementById('".$parentControlName."').value= '".$filePrefix."'+selectedFile;
	if(parentControlName2.length > 0) {
		window.opener.document.getElementById(parentControlName2).value='';
	}

	".$updateCommand."

	window.close();
}
function removeDir() {
	launchDirDeletionWindow();
}
function moveDir() {
  launchDirMovingWindow();
}
function createSubDir() {
	vars = 'type=dir&name='+currentDir;
  openWindow('create_node.php?'+'mode=ask_create_node&'+vars,330, 150, 0, 0);
}
function uploadFile() {
	launchCreateNodeWindow('type=file&name='+currentDir);
}
function multipleUpload() {
	var repositoryType = '".$repositoryType."';
	var uploadType = 1;
	if(repositoryType == '".IMAGES_FOLDER."') {
		uploadType = 2;
	}
  document.getElementById('sbw_1').contentWindow.openWindow('multiple_upload.php?path='+currentDir+'&upload_type='+uploadType,635, 302, 0, 0);
}
function refreshFrame() {
	var temp = document.getElementById('sbw_1').src;
	document.getElementById('sbw_1').src = '';
	document.getElementById('sbw_1').src = temp;
}
";
	$scripts->addLine($line);


	$manager->addScripts($scripts);


	echo $manager->getHTML();
}
?>