<?php 

if(function_exists('update_session_useraccess') !== true)
{
	function update_session_useraccess($conn)
	{
		error_log ( "### update_session_useraccess ###" );

		error_log ( " id : ".$_SESSION['id'] );

		$_SESSION['deplistid'] = '';
		$_SESSION['deplisttagid'] = '';
		$_SESSION['deplistid_excl'] ='';
		$_SESSION['deplisttagid_excl'] = '';
		$_SESSION['insttaglistid'] = '';
		$_SESSION['insttaglistid_excl'] = '';

		$sql = "select string_agg (dep_id::text,',') as depidlist ,string_agg (tl.tag_id ::text,',') as tagidlist from v_staff_member_depaccess,tag_link tl where tl.ext_id = dep_id and tl.type = 'department' and staff_id = {$_SESSION['id']} group by staff_id;";

		if($query = pg_query($conn,$sql))
		{
			if($row2 = pg_fetch_row($query))
			{
					$_SESSION['deplistid'] = $row2[0];
					$_SESSION['deplisttagid'] = $row2[1];
			}
		}

		$sql = "select string_agg (ext_id::text,',') as depidlist ,string_agg (tag_id ::text,',') as tagidlist
			from department,tag_link where department.removed = false and tag_link.type = 'department' and tag_link.ext_id  = department.id and not(ext_id = any ('{{$_SESSION['deplistid']}}'::int[]));";

		if($query = pg_query($conn,$sql))
		{
			if($row2 = pg_fetch_row($query))
			{
				$_SESSION['deplistid_excl'] = $row2[0];
				$_SESSION['deplisttagid_excl'] = $row2[1];
			}
		}

		$sql = "select string_agg(insttagid::text,',') from (
						select distinct tag.id as insttagid,tag.name, ('{'||(string_agg(department.id::text,',') over (partition by institution.id))||'}')::int[] <@ '{{$_SESSION['deplistid']}}'::int[] as alldepininst from institution,tag,tag_link,department where tag_link.type = 'institution'
						and tag_link.ext_id = institution.id and tag.id = tag_link.tag_id and tag.removed = false
						and department.inst_id = institution.id and department.removed = false) t where alldepininst = true;";

		if($query = pg_query($conn,$sql))
		{
			if($row2 = pg_fetch_row($query))
			{
				$_SESSION['insttaglistid'] = $row2[0];
			}
		}

		$sql =  "select string_agg(tag_id::text,',') from staff_member,institution left join department on institution.id = department.id, tag_link
	          where tag_link.type='institution' and tag_link.ext_id =institution.id and staff_member.login_role_id = 0 and department.id is null and institution.removed = false and staff_member.id = {$_SESSION['id']};";

		if($query = pg_query($conn,$sql))
		{
			if($row2 = pg_fetch_row($query))
			{
				if($_SESSION['insttaglistid'] == '')
				{
					$_SESSION['insttaglistid'] = $row2[0];
				}else{
					if($row2[0] != '')
						$_SESSION['insttaglistid'] .= ','.$row2[0];
				}
			}
		}

		$sql = "select string_agg(insttagid::text,',') from (
						select distinct tag.id as insttagid,tag.name, ('{'||(string_agg(department.id::text,',') over (partition by institution.id))||'}')::int[] <@ '{{$_SESSION['deplistid']}}'::int[] as alldepininst from institution,tag,tag_link,department where tag_link.type = 'institution'
						and tag_link.ext_id = institution.id and tag.id = tag_link.tag_id and tag.removed = false
						and department.inst_id = institution.id and department.removed = false) t where alldepininst = false";

		if($query = pg_query($conn,$sql))
		{
			if($row2 = pg_fetch_row($query))
			{
				$_SESSION['insttaglistid_excl'] = $row2[0];
			}
		}

		$_SESSION['alltagidallow'] = $_SESSION['deplisttagid'];
		if($_SESSION['alltagidallow']!= '' && $_SESSION['insttaglistid'] != '' )
				$_SESSION['alltagidallow'].=',';

		$_SESSION['alltagidallow'].= $_SESSION['insttaglistid'];

		$_SESSION['alltagiddeny'] = $_SESSION['deplisttagid_excl'];
		if($_SESSION['alltagiddeny']!= '' && $_SESSION['insttaglistid_excl'] != '' )
				$_SESSION['alltagiddeny'].=',';

		$_SESSION['alltagiddeny'].= $_SESSION['insttaglistid_excl'];


		$sql = "select theaccess.inst_id,v_fullinfo_department.inst_name, v_fullinfo_department.dep_name, alldep::integer from (
	 select inst_id,taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) as alldep,dep_id, sum((tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]))::integer) over (partition by inst_id) as nbr
	 from v_taglink_instdep  where taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) or tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]) and instordepremoved  = false
	 ) theaccess,v_fullinfo_department where theaccess.inst_id = v_fullinfo_department.inst_id and v_fullinfo_department.dep_id = theaccess.dep_id and instordepremoved = false;";
	 	
	 	$listInstitution = array();
		
		if($query = pg_query($conn,$sql))
		{
			while($row = pg_fetch_row($query))
			{
	        if(!array_key_exists($row[0],$listInstitution))
	        {
	          $tt = new stdClass();
	          $tt->name =trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[1],ENT_QUOTES)));
						$tt->checked = $row[3];
	          $tt->children = array();
	          $listInstitution[$row[0]] = $tt;
	        }
					$institution = &$listInstitution[$row[0]];
					$institution->children[] = trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[2],ENT_QUOTES)));
			}
		}
		
		$_SESSION['useraccessdetails'] = $listInstitution;

		error_log ( " alltagidallow : ".$_SESSION['alltagidallow'] );
	}

}

if(function_exists('create_update') !== true)
{
	function create_update($taglist, $tagidallow,$tagiddeny,$taglinktype, $tagextid)
	{

		$sql = "({$taglist}),({$tagidallow}),({$tagiddeny}),{$taglinktype},{$tagextid}";

		$sql = "";
		$tagnottoup  = $taglist;

		if($tagnottoup != '' && $tagiddeny != '')
			$tagnottoup.=',';

		$tagnottoup .= $tagiddeny;

		if($tagnottoup != '')
		{
			$sql .= "delete from tag_link where type = '{$taglinktype}' and ext_id = {$tagextid} and tag_id not in({$tagnottoup});";
		}else{
			$sql .= "delete from tag_link where type = '{$taglinktype}' and ext_id = {$tagextid} and tag_id in({$tagidallow});";
		}


		if($taglist != '')
		{
		  $sql .= "insert into tag_link(type,ext_id,tag_id)
		    select '{$taglinktype}',{$tagextid}, tag.id from tag left join tag_link on tag_link.tag_id = tag.id and tag_link.type =  '{$taglinktype}' and  tag_link.ext_id = {$tagextid}
		    where  tag.id in ({$taglist}) and tag.removed = false and tag_link.ext_id is null;";
		}
		return $sql;
	}
}

function create_translate_xml_js_function()
{
	$l = 'en';
	if(isset($_GET['l']))
		$l = $_GET['l'];

	echo "	function translate_xml(link)";
	echo "{";
	echo "return \"{$GLOBALS["EOQUAL_ROOT"]}/Common/translatexml.php?l={$l}&url=\"+link;";
	echo "}";
}

function RightsCheck ( $view )
{
	if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== TRUE)
		exit ();

	if ( $view != "" )
	{
		if ( !isset($_SESSION['view'][$view]) || $_SESSION['view'][$view] != 1 )
		{
			error_log ( "Access prohibited (".$view.") !!!" );		
			exit ();
		}
	}
}

?>