<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


include("../conf/preferences.php");
session_name(SYS_APP_SESSNAME);
session_start();

include("../conf/connections.php");
include("../phplib/auth.php");
require_once("../phplib/utils.php");
include("../conf/langs/".$langs[$_SESSION['userlang']][0]."/MAIN.php");
include("../conf/langs/".$langs[$_SESSION['userlang']][0]."/codeeditor.php");
require_once("../core/plugins.php");
error_reporting(0);		// ojo, ñapa

function addToModel($item){
	global $model;
	$data=array();
	$archivo="../../" . $item['path'];
	
	$partes_ruta=pathinfo($archivo);
	
	$data['filename']=				$partes_ruta['basename'];
	if(isset($item['title'])) $data['title']=(string)$item['title'];
	$data['filepath']=				$partes_ruta['dirname'];
	$data['filepath_complete']=		$data['filepath']. "/" . $data['filename'];
	$data['filesize']=				filesize($archivo);
	$data['filectime']=				date("Y-m-d H:i:s",filectime($archivo));
	$data['fileext']=				$partes_ruta['extension'];
	$data['filemime']=				mime_content_type($archivo);
	if(isset($item->extra)){
		$data['extra']=array();
		foreach($item->extra->children() as $extrainfo){
			$data['extra'][$extrainfo->getName()]=(string)$extrainfo;
		}
	}
	$model[]=$data;
}

function sksort(&$array, $subkey="id", $sort_ascending=false) {
	if (count($array))  $temp_array[key($array)] = array_shift($array);
	foreach($array as $key => $val){
		$offset = 0;
		$found = false;
		foreach($temp_array as $tmp_key => $tmp_val){
			if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey])){
				$temp_array = array_merge(	(array)array_slice($temp_array,0,$offset),
											array($key => $val),
											array_slice($temp_array,$offset)
				);
				$found = true;
			}
			$offset++;
		}
		if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
	}
	if ($sort_ascending) $array = array_reverse($temp_array);
	else $array = $temp_array;
}

if(!isset($_REQUEST['resId'])) header("Location:error.php");
$resId=$_REQUEST['resId'];
$conf=simplexml_load_file("../conf/resources/".$langs[$_SESSION['userlang']][0]."/".$_SESSION['conf'][$resId]->masterview);
$titulogeneral=$conf->title!=NULL ? $conf->title : $_SESSION['conf'][$resId]->title;

$model=array();
$errores=array();
clearstatcache();
foreach($conf->data->connector as $connector){
	$conn_type=(string)$connector['type'];
	switch($conn_type){
		case "filelist":
			foreach($connector->file as $item){
				if(file_exists("../../" . $item['path'])) addToModel($item);
			}
			break;
		case "folder":
			$files = glob("../../" . $connector['path'] . "{" . $connector['pattern'] . "}", GLOB_BRACE);
			foreach($files as $item){
				if(is_dir($item)) continue;
				$dd=array();
				$dd['path']=str_replace("../../", "", $item);
				addToModel($dd);
			}
			break;
		case "ftp":
			break;
		case "mysql":
			break;
	}
}
if(isset($conf->data['sort_on'])){
	$ascending=(string)$conf->data['sort_ascending']=="true";
	sksort($model, (string)$conf->data['sort_on'], $ascending);
}

for($i=count($model)-1;$i>0;$i--){
	if($model[$i]['filepath_complete']==$model[$i-1]['filepath_complete']) unset($model[$i]);
}
$accion="";
if(isset($_REQUEST['action'])) $accion=$_REQUEST['action'];
$resultado=NULL;
switch($accion){
	case "loadfile":

		$file=file_get_contents($_REQUEST['url']);
		if($file!==false){
			$resultado->result="ok";
			$resultado->contents=$file;
		}else{
			$resultado->result="ko";
			$resultado->msg=$EKL['CODE_EDIT']['NOFILE'];
		}
		header("Content-type: text/plain");
		echo json_encode($resultado);
		exit();
		break;
	case "savefile":
		$errores='';
		if(!file_exists($_REQUEST['url'])){
			$errores.=$EKL['CODE_EDIT']['NOFILE'];
		}else{
			$file=file_put_contents($_REQUEST['url'],$_REQUEST['data']);
			if($file===false) $errores.=$EKL['CODE_EDIT']['FILE_WRITE_ERROR'];
		}
		if($errores==""){
			$resultado->result="ok";
		}else{
			$resultado->result="ko";
			$resultado->msg=$EKL['CODE_EDIT']['NOFILE'];
		}
		header("Content-type: text/plain");
		echo json_encode($resultado);
		exit();
		break;
	case "":
	default:
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title><? echo $titulogeneral ?></title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="../resources/themes/default/common.css" rel="stylesheet" type="text/css" media="screen" />
	<link href="../resources/themes/default/main.css" rel="stylesheet" type="text/css" media="screen" />
	<link href="../resources/themes/default/form_screen.css" rel="stylesheet" type="text/css" media="screen" />
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.custom.css" rel="stylesheet" />
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery-ui.ekain.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/jquery-1.7.2.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/jquery.blockUI.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/js/jquery-ui-1.8.21.custom.min.js" ></script>
	<script type="text/javascript" src = "../jslib/jq/ui/jquery.ui.selectmenu.js" ></script>
	<link type="text/css" href="../jslib/jq/ui/css/<? echo UI_THEME ?>/jquery.ui.selectmenu.css" rel="stylesheet" />
	<script type="text/javascript" src = "../jslib/jq/ui/i18n/jquery.ui.datepicker-<? echo $langs[$_SESSION['userlang']][0] ?>.js" ></script>
	<script type="text/javascript" src="../jslib/codemirror/lib/codemirror.js"></script>
	<link rel="stylesheet" href="../jslib/codemirror/lib/codemirror.css">
	<script type="text/javascript" src="../jslib/codemirror/mode/javascript/javascript.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/css/css.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/xml/xml.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/htmlmixed/htmlmixed.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/clike/clike.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/php/php.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/mysql/mysql.js"></script>
	<script type="text/javascript" src="../jslib/codemirror/mode/shell/shell.js"></script>
	<script src="../jslib/codemirror/lib/util/searchcursor.js"></script>
    <script src="../jslib/codemirror/lib/util/match-highlighter.js"></script>
	
	<script type="text/javascript" src="../jslib/utils.js"></script>
	<script src="../jslib/swfobject2.js" type="text/javascript"></script>
	<script type="text/javascript">
	var model=<? echo json_encode($model); ?>;
	var currentDocChanged=false;
	var currentDoc={};
	var editorTitle='<? echo $EKL['CODE_EDIT']['EDITOR_TITLE'] ?>';
	var editModes={'php':'php', 'js':'javascript', 'htm':'htmlmixed', 'html':'htmlmixed', 'css':'css', 'xml':'xml'};

	$(document).ready(function(){
		$('button, input:submit, input:button, input:reset, .button, .link_button').button();
		$('.btn_toolbar').button( "option", "disabled", true );
		$('#fileload').button( "option", "disabled", true );
		$('#table_head_title').text(editorTitle);
		
		$('#filelist').empty();
		$.each(model, function(index, objeto) { 
			$('#filelist').append($("<option></option>").attr("value",index).text(objeto['filename']))
		});
		
		$('#filelist').change(function(){
			var index=parseInt($(this).val());
			currentDoc=model[index];
			$('#fileload').button( "option", "disabled", false );
			var cadena="";
			cadena+="<p><strong>"+currentDoc.filename+"</strong></p>";
			if(currentDoc.title!=undefined) cadena+="<p>" + currentDoc.title+"<p>";
			cadena+="<p><? echo $EKL['CODE_EDIT']['DET_FOLDER'] ?>:<br />" + currentDoc.filepath+"/</p>";
			var fsize=(parseFloat(currentDoc.filesize)/1024).toFixed(2);
			cadena+="<p><? echo $EKL['CODE_EDIT']['DET_SIZE'] ?>:<br />" + fsize+" kb</p>";
			cadena+="<p><? echo $EKL['CODE_EDIT']['DET_DATE_MODIFIED'] ?>:<br />" + currentDoc.filectime+"</p>";
			cadena+="<p><? echo $EKL['CODE_EDIT']['DET_MIMETYPE'] ?>:<br />" + currentDoc.filemime+"</p>";
			$('#filedetails').html(cadena);
		});
		
		var conf={
			'lineNumbers':true,
			'lineWrapping':true,
			'height':'500px',
			'readOnly': 'nocursor',
			'onChange':function(editor,obj){
				currentDocChanged=true;
				$('#table_head_title').text(currentDoc.filename + " *");
			},
			onCursorActivity: function() {
				cm.setLineClass(hlLine, null, null);
				hlLine = cm.setLineClass(cm.getCursor().line, null, "activeline");
				cm.matchHighlight("CodeMirror-matchhighlight");
			}
		};
		var cm = CodeMirror.fromTextArea(document.getElementById('playground'), conf);
		var hlLine = cm.setLineClass(0, "activeline");
		$(cm.getScrollerElement()).height(500);
		cm.refresh();

		$('#fileload').click(function(){
			$(this).blur();
			if(currentDoc.filepath==undefined) return;
			$.blockUI({ message: null });
			$.post("codeedit.php", {'resId':'<? echo $_REQUEST['resId'] ?>', 'action':'loadfile', 'url': currentDoc.filepath+'/'+currentDoc.filename},function(data){
				if(data.result=="ok"){
					cm.setOption('mode', editModes[currentDoc.fileext]);
					cm.setOption('readOnly', false);
					cm.setValue(data.contents);
					$('.btn_toolbar').button( "option", "disabled", false );
					$('#table_head_title').text(currentDoc.filename);
					currentDocChanged=false;
				}else{
					alert(data.msg);
				}
				$.unblockUI();
			},"json");
		});
		
		$('#btn_close').click(function(){
			$(this).blur();
			cm.setValue('');
			cm.setOption('readOnly', 'nocursor');
			currentDoc={};
			currentDocChanged=false;
			$('.btn_toolbar').button( "option", "disabled", true );
			$('#table_head_title').text(editorTitle);
			$('#filedetails').html("");
			$("#filelist").find("option:selected").prop("selected", false);
		});
		
		$('#btn_revert').click(function(){
			$(this).blur();
			if(currentDocChanged==true){
				var x=confirm("<? echo $EKL['CODE_EDIT']['CONFIRM_REVERT'] ?>");
				if(x){
					$('#fileload').trigger('click');
				}else{
					// ...
				}
			}
		});
		
		$('#btn_save').click(function(){
			$(this).blur();
			if(currentDoc.filepath==undefined || currentDocChanged==false) return;
			$.blockUI({ message: null });
			$.post("codeedit.php", {
				'resId':'<? echo $_REQUEST['resId'] ?>', 
				'action':'savefile', 
				'url': currentDoc.filepath+'/'+currentDoc.filename, 
				'data':cm.getValue()
			},function(data){
				if(data.result=="ok"){
					currentDocChanged=false;
					$('#table_head_title').text(currentDoc.filename);
				}else{
					alert(data.msg);
				}
				$.unblockUI();
			},"json");
		});
		
	});
	</script>
	<style type="text/css">
	.activeline {background: #e8f2ff !important;}
	span.CodeMirror-matchhighlight { background: #e9e9e9 }
	.CodeMirror-focused span.CodeMirror-matchhighlight { background: #e7e4ff; !important }
	</style>
</head>

<body id="cuerpo" <? echo isset($conf->layout->class)? 'class="'.$conf->layout->class.'"' : 'bkg-master-1' ?>>
<div id="pageBar">
	<h1><? echo $titulogeneral ?></h1>
	<div style="position:absolute; right:5px; top:3px;">
	<? if($conf->layout->help_topic!="" && $conf->layout->help_topic!=NULL){ ?><a href="#" onclick="javascript:openPopupWindow('../help/loader.php?topic=<? echo $conf->layout->help_topic ?>','helpWindow',500,500,true,'scrollbars')"><img src="../resources/themes/default/icon_help.png" style="border:0" /></a><? } ?>
	</div>
</div>
<table cellpadding="0" cellspacing="0" style="width:100%" >
<tr>
<td id="panel_central" valign="top">
	<form name="dataform" id="dataform" method="post" enctype="application/x-www-form-urlencoded" action="<? echo $_SERVER['REQUEST_URI'] ?>">
	<? if(isset($conf->intro)) echo "<div class='introbox sombra roundcorners bkg_icon_info'>" . Content::parse($conf->intro) . "</div>" ?>
	<? $anchura=$conf->layout->width!=NULL ? (string)$conf->layout->width : "100%" ?>
	<table width="<? echo $anchura  ?>" border="0" align="center" cellspacing="0" cellpadding="0" id="tabla" class="sombra tablaformulario ui-corner-top">
		<thead>
		<tr>
			<td class="header_caption header_caption_bkg ui-corner-top" id="table_head_title"></td>
		</tr>
		</thead>
		
		
		<tbody id="table_body" class="innertbody">
		<tr class="row1">
			<td>
				<textarea class="animated ta_complete" name="playground" id="playground" style="height:500px;"></textarea>
			</td>
		</tr>
		</tbody>
		
		
		<tfoot id="table_foot">
		<tr>
			<td class="ui-state-default footer">
				<input type="button" id="btn_save" name="btn_save" value="<? echo $EKL['CODE_EDIT']['BTN_SAVE'] ?>" class="but_medium bold btn_toolbar" />
				<input type="button" id="btn_revert" name="btn_revert" value="<? echo $EKL['CODE_EDIT']['BTN_REVERT'] ?>" class="but_medium bold btn_toolbar" />
				<input type="button" id="btn_close" name="btn_close" value="<? echo $EKL['CODE_EDIT']['BTN_CLOSE'] ?>" class="but_medium bold btn_toolbar" />
			</td>
		</tr>
		</tfoot>

	</table>
	</form>
</td>
<td id="panel_lateral" valign="top">
	<div class="secc_container" >
		<div class="secc_title header_caption_bkg" onclick="toggleVis('secc1')">&nbsp;<? echo $EKL['CODE_EDIT']['FILE_LIST'] ?></div>
		<div class="secc_content" id="secc1">
			<? if(count($model)>0){ ?>
			<select name="filelist" id="filelist" multiple="multiple" size="<? echo $conf->layout->fb_size ?>" class="animated select_large" style="margin-bottom:10px"></select>
			<input type="button" name="fileload" id="fileload" class="but_default wpc100 bold" value="<? echo $EKL['CODE_EDIT']['BTN_LOAD'] ?>" />
			<div id="filedetails"></div>
			<? } ?>
		</div>
	</div>
</td>
</tr>
</table>
</body>
</html>
<?
}
?>