<?php
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");

$interviewer = '_Interviewer';
$intStructure = '_InterviewerStructure';

class wupTreeManipulator extends TreeDataManipulator
{
	/**
	 * additional function for selecting an item
	 * @see TreeDataManipulator::selectAction()
	 */
	function selectAction()
	{
		$id = $_POST['node'];
		$this->db->LogWrite($id,false,"selectAction -> _POST['node']");
		
		if($id == 2 || substr($id,0,6) == 'design' ) // if Designer is selected
		{
			$this->table = '_DesignerTemplates';
			$this->lab = 'name';
			$_POST['boldRoots'] = false;
			
			if($id == 2)
				$_POST['node'] = 0;
			else 
				$_POST['node'] = substr($id,7);
			
			$this->idPrefix = 'design_';
		}
		else if($id == 33 || substr($id,0,9) == 'interview' ) // if Groups is selected
		{
			$this->table = '_groups';
			$_POST['boldRoots'] = false;
			
			if($id == 33)
				$_POST['node'] = 0;
			else 
				$_POST['node'] = substr($id,10);
			
			$this->idPrefix = 'interview_';
			$_POST['RMorder'] = 'is_leaf ASC,idLab ASC';
		}
		elseif ($id == 70 || substr($id,0,10) == 'userDefine') // if user define module is selected
		{
			$this->table = '_userDefineModules';
			$_POST['boldRoots'] = false;
			if($id == 70)
				$_POST['node'] = 0;
			else 
				$_POST['node'] = substr($id,11);
						
			$this->idPrefix = 'userDefine_';
			$_POST['RMorder'] = 'is_leaf ASC,idLab ASC';
		}
		else if($id == 65 || substr($id,0,4) == 'mask') // if Masks is selected
		{
			// prepare tree for Mask Templates
			$this->table = '_MaskTemplates'; // table for Mask Templates
			$this->lab = 'name'; // label comes from this field
			$_POST['boldRoots'] = false;
			
			if($id == 65)
				$_POST['node'] = 0;
			else 
				$_POST['node'] = substr($id,5);
			
			$this->idPrefix = 'mask_';
		}
		else // any other selection
		{
			$this->append = array('allowDrag'=>false);
			parent::selectAction();
			//let's get my rights :)
			//first let's find out all the groups I have
			$this->db->ChangeDatabase(DB_WARPIT_MAIN);
			$userId = $_SESSION['UserInfo']['id'];
			$groupId = $this->db->get( '_user',$userId,permissionGroup );
			$groups[] = $groupId;
			while ($groupId = $this->db->get( '_PermissionGroups',$groupId,'id_sup' ))
				$groups[] = $groupId;
			$bla = array();
			foreach ($this->nodes as $id => &$menu) {
				//find out if I have the right
					$sql = $this->db->SQLexecute( "SELECT deny FROM _PermissionLink WHERE deny=1 "
					     . "AND id_permission = {$menu['id']} AND p_type=1 AND (id_user=$userId "
					     . "OR id_permission_group IN (".implode(',',$groups).") )" );
				$res = $this->db->fetchRow($sql);
				if($res[0] != 1)
					$bla[] = $menu;
				;
			}
			
			return json_encode($bla);
			
		}
		
		return parent::selectAction();
	}
	/**
	 * additional function for inserting an item into the tree
	 * @see TreeDataManipulator::insertItemAction()
	 */
	function insertItemAction()
	{
		
		//becouse the nodes have design_ prefix!
		if( substr( $_POST['nodeId'],0,6 ) == 'design' || $_POST['nodeId'] == 2)
		{
			$this->table = '_DesignerTemplates';
			$this->lab = 'name';
			if( substr( $_POST['parId'],0,6 ) == 'design') $_POST['parId'] = substr( $_POST['parId'],7 ); else $_POST['parId'] = 0;
		
		
			if( substr( $_POST['nodeId'],0,6 ) == 'design' ) $_POST['nodeId'] = substr( $_POST['nodeId'],7 ); else $_POST['nodeId'] = 0;
			
			return parent::insertItemAction();
		}
		else if( substr( $_POST['nodeId'],0,9 ) == 'interview' || $_POST['nodeId'] == 33)
		{
			$this->table = '_groups';
			//$this->lab = 'name';
			if( substr( $_POST['parId'],0,9 ) == 'interview') $_POST['parId'] = substr( $_POST['parId'],10 ); else $_POST['parId'] = 0;
		
		
			if( substr( $_POST['nodeId'],0,9 ) == 'interview' ) $_POST['nodeId'] = substr( $_POST['nodeId'],10 ); else $_POST['nodeId'] = 0;
			
			return parent::insertItemAction();
		}
		else if( substr( $_POST['nodeId'],0,10 ) == 'userDefine' ||  $_POST['nodeId'] == 70) {
			$this->table = '_userDefineModules';
			if( substr( $_POST['parId'],0,10 ) == 'userDefine') $_POST['parId'] = substr( $_POST['parId'],11 ); else $_POST['parId'] = 0;
			if( substr( $_POST['nodeId'],0,10 ) == 'userDefine' ) $_POST['nodeId'] = substr( $_POST['nodeId'],11 ); else $_POST['nodeId'] = 0;
			
			$insertExec = parent::insertItemAction();
			// write additional info about the inserted row
			$this->setUserDefine_fileName(); 
			
			return $insertExec;
		} 
		else if( substr( $_POST['nodeId'],0,4 ) == 'mask' || $_POST['nodeId'] == 65)
		{
			$this->table = '_MaskTemplates';
			$this->lab = 'name';
			if( substr( $_POST['parId'],0,4 ) == 'mask') $_POST['parId'] = substr( $_POST['parId'],5 ); else $_POST['parId'] = 0;
		
		
			if( substr( $_POST['nodeId'],0,4 ) == 'mask' ) $_POST['nodeId'] = substr( $_POST['nodeId'],5 ); else $_POST['nodeId'] = 0;
			
			return parent::insertItemAction();
		}
		return "{success:false,error:'Unknown insert item!'}";
		
	}
	/**
	 * additional function for deleting a node in the tree
	 * @see TreeDataManipulator::deleteAction()
	 */
	function deleteAction()
	{
		if( substr( $_POST['nodeId'],0,6 ) == 'design' || $_POST['nodeId'] == 2)
		{
			$this->table = '_DesignerTemplates';
			if( substr( $_POST['nodeId'],0,6 ) == 'design' ) 
				$_POST['nodeId'] = substr( $_POST['nodeId'],7 ); 
			else $_POST['nodeId'] = 0;
		}
		else if( substr( $_POST['nodeId'],0,9 ) == 'interview' || $_POST['nodeId'] == 33)
		{
			$this->table = '_groups';
			if( substr( $_POST['nodeId'],0,9 ) == 'interview' ) 
				$_POST['nodeId'] = substr( $_POST['nodeId'],10 ); 
				else $_POST['nodeId'] = 0;
			
			
			$sql = "DELETE FROM _group_link WHERE id_group = ".$_POST['nodeId'];
			$this->db->SQLexecute($sql);
			
		}
		else if( substr( $_POST['nodeId'],0,10 ) == 'userDefine' || $_POST['nodeId'] == 70)
		{
			$this->table = '_userDefineModules';
			if( substr( $_POST['nodeId'],0,10 ) == 'userDefine' ) 
				$_POST['nodeId'] = substr( $_POST['nodeId'],11 ); 
				else $_POST['nodeId'] = 0;
			
			
			$sql = "DELETE FROM _group_link WHERE id_group = ".$_POST['nodeId'];
			$this->db->SQLexecute($sql);
			
		}
		else if( substr( $_POST['nodeId'],0,4 ) == 'mask' || $_POST['nodeId'] == 65)
		{
			$this->table = '_MaskTemplates';
			if( substr( $_POST['nodeId'],0,4 ) == 'mask' ) 
				$_POST['nodeId'] = substr( $_POST['nodeId'],5 ); 
			else $_POST['nodeId'] = 0;
		}
		
		parent::deleteAction();
	}
	/**
	 * additional function for copying an item in the tree
	 * 
	 */
	function copyItemAction()
	{
		if( substr( $_POST['nodeId'],0,6 ) == 'design' || $_POST['nodeId'] == 2)
		{
			$this->table = '_DesignerTemplates';
			$this->lab = 'name';
			//because the nodes have design_ prefix!
			if( substr( $_POST['parId'],0,6 ) == 'design' ) $_POST['parId'] = substr( $_POST['parId'],7 ); else $_POST['parId'] = 0;
			if( substr( $_POST['nodeId'],0,6 ) == 'design' ) $_POST['nodeId'] = substr( $_POST['nodeId'],7 ); else $_POST['nodeId'] = 0;
		}
		else if( substr( $_POST['nodeId'],0,4 ) == 'mask' || $_POST['nodeId'] == 65)
		{
			$this->table = '_MaskTemplates';
			$this->lab = 'name';
			//because the nodes have design_ prefix!
			if( substr( $_POST['parId'],0,4 ) == 'mask' ) $_POST['parId'] = substr( $_POST['parId'],5 ); else $_POST['parId'] = 0;
			if( substr( $_POST['nodeId'],0,4 ) == 'mask' ) $_POST['nodeId'] = substr( $_POST['nodeId'],5 ); else $_POST['nodeId'] = 0;
		}
        
		$return = parent::insertItemAction();
		if($this->insertId)
		{
			
			$getNewSql = "SELECT template_xml FROM $this->table WHERE id = ".$_POST['nodeId'];
			
				If (!$rs = $this->db->SQLexecute($getNewSql)) {return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';	}	
				if( !$row = $this->db->fetchAssoc($rs)){return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';}
				
				$sql = "UPDATE $this->table SET template_xml = '{$row['template_xml']}' WHERE id = $this->insertId";
				$this->db->SQLexecute($sql);
		}
        print "/*" . $this->sql . "*/";
		return $return;
		
	}
	/**
	 * additional function for moving a node in the tree
	 * @see TreeDataManipulator::moveNodeAction()
	 */
	function moveNodeAction()
	{
		$nodeId = $_POST['nodeId'];
		
		if(substr($nodeId,0,6) == 'design' )
		{
			$this->table = '_DesignerTemplates';
			$_POST['nodeId'] = substr($nodeId,7);
			$_POST['targetId'] = substr($_POST['targetId'],7);
		}
		else if(substr($nodeId,0,9) == 'interview' )
		{
			$this->table = '_groups';
			$_POST['nodeId'] = substr($nodeId,10);
			$_POST['targetId'] = substr($_POST['targetId'],10);
		}
		else if(substr($nodeId,0,10) == 'userDefine' )
		{
			$this->table = '_userDefineModules';
			$_POST['nodeId'] = substr($nodeId,11);
			$_POST['targetId'] = substr($_POST['targetId'],11);
		}
		else if(substr($nodeId,0,4) == 'mask' )
		{
			$this->table = '_MaskTemplates';
			$_POST['nodeId'] = substr($nodeId,5);
			$_POST['targetId'] = substr($_POST['targetId'],5);
		}
		return parent::moveNodeAction();
	}
	
	public function editWCmenuAction() {
		$tmp = explode("_",$_POST['nodeId']);
		$idNode = $tmp[1];
		
		$_POST['nodeId'] = $idNode;
		$this->table = "_userDefineModules";
		
		return parent::editAction();
	}
	
	
	/**
	 * check for non english letters and return false, if found
	 *
	 */
	protected function english_letters($letter) {
		 $all_letters = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","z","x","y","_");
		 if (in_array($letter,$all_letters))
		 	return true;
		 else 
		 	return false;
	}
	
	
	/**
	 * extract file name for user define progrm out of script menu name 
	 *
	 */
	protected function setUserDefine_fileName() {
		$file_name = "";
		$text = str_replace(" ","_",$_POST['nodeText']);
		$text = strtolower($text);
		for ($i=0; $i<strlen($text); $i++) {  
		    if ($this->english_letters($text[$i]) == true) $file_name .= $text[$i];  
		}  
		$file_name .= ".php"; 
		$sql = "UPDATE _userDefineModules SET file_name='$file_name', module_type=2 WHERE id=".$this->insertId." AND is_leaf=1";
		$this->db->SQLexecute($sql);
		
		return fileName;
	}
	
	
}

	
$db->ChangeDatabase($_POST['database']);

if($_POST['RMcomp']=='tree')
	$manipulator = new wupTreeManipulator($db,$_POST['RMtable']);

$comm = $_POST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else 
{
	
	echo '{success:false,error:"Unknown action!"}';	
	
}


?>
