<?
////////////////////////////////////////////////////
// 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/langs/".$langs[$_SESSION['userlang']][0]."/MAIN.php");
include("../conf/connections.php");
include("../phplib/auth.php");
require_once("../phplib/utils.php");
require_once("../core/plugins.php");

$mindepth=array();		
$accion=$_REQUEST['action'];
$resId=$_REQUEST['resId'];
if(isset($_REQUEST['parentId'])) $parentId=$_REQUEST['parentId'];
$conf=simplexml_load_file("../conf/resources/".$langs[$_SESSION['userlang']][0]."/".$_SESSION['conf'][$resId]->masterview);

$obj=NULL;		
$result="";		

switch($accion){
	case "getTree":
		$result="<ul>";
		$padre=isset($_REQUEST['parentId']) ? $_REQUEST['parentId'] : $conf->data->root_id;
		$maxdepth=isset($_REQUEST['maxDepth']) ? $_REQUEST['maxDepth'] : 0;
		$result.=getTree($padre);
		$result.="</ul>";
		break;
	case "getTree2":
		$result="<ul>";
		$padre=isset($_REQUEST['parentId']) ? $_REQUEST['parentId'] : $conf->data->root_id;
		$maxdepth=isset($_REQUEST['maxDepth']) ? $_REQUEST['maxDepth'] : 0;
		$result.=getTree2($padre);
		$result.="</ul>";
		break;
	case "rebuildTree":
		$result="<ul><li>".rebuild_tree("cra_z_help", 0, 0, 0, "id", "lft", "rgt", "padre", "nivel", "orden")."</li></ul>";
		break;
	case "remove":
		$result=deleteNode($_REQUEST['id']);
		break;
	case "move":
		$result=moveNode($_REQUEST['id'], $_REQUEST['padre'], $_REQUEST['pos']);
		break;
}


function rebuild_tree($tabla, $parent, $left, $depth=0, $keyfield, $lftfield, $rgtfield, $parentfield, $depthfield, $orderfield=NULL) {
	$right = $left+1;				// el rgt de este nodo es el lft + 1
	$orderby=$orderfield==NULL ? '' : " ORDER BY $orderfield";
	$sql="SELECT $keyfield FROM $tabla WHERE $parentfield='$parent' $orderby;";
	$result = mysql_query($sql) or die($sql);
	while ($row = mysql_fetch_array($result)) {	
		$right = rebuild_tree($tabla, $row[$keyfield], $right, $depth+1, $keyfield, $lftfield, $rgtfield, $parentfield, $depthfield, $orderfield);
	}
	$sql="UPDATE $tabla SET $lftfield=$left, $rgtfield=$right, $depthfield=$depth WHERE $keyfield='$parent'";
	mysql_query($sql) or die($sql);
	return $right+1;				
}


function getTree($padre=NULL){
	global $conf; global $maxdepth; global $mindepth; $cadena='';
	if($padre==NULL) $padre=$conf->data->root_id;
	$sql=$conf->data->sql . " ORDER BY " . $conf->data->orderby;
	$sql=str_replace("{@root}", $padre, $sql);
	$q=mysql_query($sql);
	while($f=mysql_fetch_assoc($q)){
		if(isset($conf->data->field_depth)){
			$mindepth[]=$f[(string)$conf->data->field_depth];
			if($maxdepth>0 && $f[(string)$conf->data->field_depth]-min($mindepth)>=$maxdepth) break;
		}
		$id=$f[(string)$conf->data->field_key];
		$tiponodo= "folder";	
		$parent= $padre=='0' ? '' : $padre;
		$nombre='root'.$id;
		$titulo=$f['titulo'];
		if(isset($conf->data->field_icon) && $f[(string)$conf->data->field_icon]!=''){
			$icono=$f[(string)$conf->data->field_icon];
		}else{
			$icono="document_plain.png";
		}
		if($f['href']!='') $link=$link="../".$f['href'] . ($tiponodo!="folder" ? '?resId=' . $id : '#');
		$marco=$f['target']!='' ? $f['target'] : 'mainFrame';
		$link=$_SERVER['PHP_SELF']."?".changeUrlParam('parentId',$id);
		$clase=$f['children']>0 ? "class='jstree-closed'" : "";
		$showchildren=$conf->layout->show_children=="true" ? " [{$f['children']}]" : "";
		
		$cadena.="<li id='phtml_{$id}' $clase><a href='$link' rel='{$tiponodo}' target='self'><img src='../resources/icons16/{$icono}' class='iconomenu' /> {$titulo}{$showchildren}</a>\n";
		
		if($tiponodo=="folder" && $f['children']>0){	
			$cadena.="<ul>\n";
			if($f['children']>0) $cadena.=getTree($id);
			$cadena.="</ul>\n";
		}
		$cadena.="</li>\n";
	}
	return $cadena;
}

function deleteNode($id){
	global $conf; global $resId;
	$d=$conf->data;
	$orderfield=(string)$d->field_order;
	$table=(string)$d->table;
	$keyfield=(string)$d->field_key;
	$depfield=(string)$d->field_dependency;
	$sql="SELECT * FROM ".(string)$d->table." WHERE ".(string)$d->field_key."='$id'";
	$q=mysql_query($sql);
	if(mysql_num_rows($q)>0){
		$f=mysql_fetch_assoc($q);
		beforeDelete($f);
		mysql_query("DELETE FROM ".(string)$d->table." WHERE ".(string)$d->field_key."='$id'");
		afterDelete($f);
		$result=recursiveErase((string)$d->table, (string)$d->field_key, $id, (string)$d->field_dependency);
		rebuild_tree($table, 0, 0, 0, $keyfield, (string)$d->field_lft, (string)$d->field_rgt, $depfield, (string)$d->field_depth, $orderfield);
		$result="ok";
	}else{
		$result="ko: no existe ese nodo";
	}
	return $result;
}

function moveNode($id, $padre, $pos){
	global $conf; global $resId; $cadena='';
	$d=$conf->data;
	$orderfield=(string)$d->field_order;
	$table=(string)$d->table;
	$keyfield=(string)$d->field_key;
	$depfield=(string)$d->field_dependency;
	$sql="SELECT $depfield FROM $table WHERE $keyfield='$id'";
	$q=mysql_query($sql);
	if(mysql_num_rows($q)>0){
		$ordarray=array(); $orden=1;
		$sql1="SELECT $keyfield FROM $table WHERE $depfield='$padre' ORDER BY $orderfield";
		$qq=mysql_query($sql1);
		if(mysql_num_rows($qq)>0){
			if($pos>=mysql_num_rows($qq)){
				$sql="SELECT MAX($orderfield) AS maxx FROM $table WHERE padre='$padre'";
				$qqq=mysql_query($sql) or die($sql);
				$fff=mysql_fetch_assoc($qqq);
				$no=(int)$fff['maxx'];
				$sql="UPDATE $table SET $depfield='$padre', $orderfield=".($no+1)." WHERE $keyfield='$id'";
				mysql_query($sql);
			}else{
				while($ff=mysql_fetch_assoc($qq)) $ordarray[]="'".$ff[(string)$d->field_key]."'";
				$yuyu=array_splice($ordarray,$pos);
				$indices=implode(",",$yuyu);
				$sql="UPDATE $table SET $orderfield=$orderfield+1 WHERE $keyfield IN({$indices})";
				$qa=mysql_query($sql);
				$sql="UPDATE $table SET $depfield='$padre', $orderfield=(SELECT $orderfield FROM (SELECT * FROM $table) AS x WHERE id={$yuyu[0]})-1 WHERE $keyfield='$id'";
				$qb=mysql_query($sql) or die(mysql_error()."\n".$sql);
			}
		}else{
			$sql="UPDATE $table SET $depfield='$padre', $orderfield=1 WHERE $keyfield='$id'";
			mysql_query($sql);
		}
		rebuild_tree($table, 0, 0, 0, $keyfield, (string)$d->field_lft, (string)$d->field_rgt, $depfield, (string)$d->field_depth, $orderfield);
		$result="ok";
	}else{
		$result="ko: movimiento no válido";
	}
	return $result;
}

function getTree2($id=NULL){
	global $conf; $cadena='';
	$sql="SELECT lft, rgt FROM ".$conf->data->table." WHERE ".$conf->data->field_key."='{$id}'";
	$r=mysql_fetch_assoc(mysql_query($sql));
	$sql="SELECT * FROM ".$conf->data->table." WHERE lft BETWEEN {$r['lft']} AND {$r['rgt']} ORDER BY lft";
	$q=mysql_query($sql) or die($sql);
	while($f=mysql_fetch_assoc($q)){
		$id=$f[(string)$conf->data->field_key];
		$tiponodo= "folder";
		$parent= $padre=='0' ? '' : $padre;
		$nombre='root'.$id;
		$titulo=$f['titulo'];
		$icono="document_plain.png";
		if($f['href']!='') $link=$link="../".$f['href'] . ($tiponodo!="folder" ? '?resId=' . $id : '#');
		$marco=$f['target']!='' ? $f['target'] : 'mainFrame';
		$link=$_SERVER['PHP_SELF']."?".changeUrlParam('parentId',$id);
		$cadena.="<li id='phtml_{$id}'><a href='$link' rel='{$tiponodo}' target='self'><img src='../resources/icons16/{$icono}' class='iconomenu' /> {$titulo}</a>\n";
		if($tiponodo=="folder"){	
			$cadena.="<ul>\n";
			if($f['hijos']>0) $cadena.=getNavTree($id);
			$cadena.="</ul>\n";
		}
		$cadena.="</li>\n";
	}
	return $cadena;
}

function beforeDelete($f){
	global $conf; global $mail; global $resId;
	if(isset($conf->data->events)){
		foreach($conf->data->events->event as $evento){
			if((string)$evento['type']!='onBeforeDelete') continue;
			if(!estaArchivoIncluido((string)$evento['src'])) include("../".$evento['src']);
			$nombreclase=(string)$evento['class'];
			$metodo=(string)$evento['method'];
			if(isset($evento['params'])){
				$params=explode("@@@",(string)$evento['params']);
				for($i=0;$i<count($params);$i++) $params[$i]=Content::parse($params[$i]);
			}else{
				$params=NULL;
			}
			$objeto=new $nombreclase();
			$objeto->resId=$resId;
			$objeto->recordset=$f;
			$objeto->mail=$mail;
			$objeto->$metodo($params);
		}
	}
	
	$sql="SELECT * FROM " . SYS_MEDIA_TABLE . " WHERE idres=$resId AND idrec={$f['id']}";
	$q=mysql_query($sql);
	while($item=mysql_fetch_assoc($q)){
		if($item['readonly']!=1){
			@unlink($item['filename']);
			mysql_query("DELETE FROM " . SYS_MEDIA_TABLE . " WHERE id={$item['id']}");
		}
	}
}
function afterDelete($f){
	global $conf; global $mail; global $resId;
	if(isset($conf->data->events)){
		foreach($conf->data->events->event as $evento){
			if((string)$evento['type']!='onAfterDelete') continue;
			if(!estaArchivoIncluido((string)$evento['src'])) include("../".$evento['src']);
			$nombreclase=(string)$evento['class'];
			$metodo=(string)$evento['method'];
			if(isset($evento['params'])){
				$params=explode("@@@",(string)$evento['params']);
				for($i=0;$i<count($params);$i++) $params[$i]=Content::parse($params[$i]);
			}else{
				$params=NULL;
			}
			$objeto2=new $nombreclase();
			$objeto2->resId=$resId;
			$objeto2->recordset=$F;
			$objeto2->mail=$mail;
			$objeto2->$metodo($params);
		}
	}
	if(SYS_LOG_OPS==true){
		registerLog($resId,3);
	}
}

function recursiveErase($table,$key,$id,$dep){
	global $conf; global $resId;
	$cadena='';
	$cadena="SELECT $key FROM $table WHERE $dep='$id'";
	$q=mysql_query($cadena) or die(mysql_error());
	while($f=mysql_fetch_array($q)){
		$resultado=recursiveErase($table,$key,$f[(string)$key],$dep);
		beforeDelete($f);
		$sql="DELETE FROM $table WHERE $key='{$f['id']}'";
		$cadena.=$sql."\n";
		$q=mysql_query($sql);
		if($q){
			afterDelete($f);
			return "ok";
		}else{
			return "ko: ".mysql_error();	
		}
	}
}

echo $result;
?>