<?php
require_once __DIR__.'/../Config/config.php';

function unaccent($str)
{
	$transliteration = array(
		'Ĳ' => 'I', 'Ö' => 'O','Œ' => 'O','Ü' => 'U','ä' => 'a','æ' => 'a',
		'ĳ' => 'i','ö' => 'o','œ' => 'o','ü' => 'u','ß' => 's','ſ' => 's',
		'À' => 'A','Á' => 'A','Â' => 'A','Ã' => 'A','Ä' => 'A','Å' => 'A',
		'Æ' => 'A','Ā' => 'A','Ą' => 'A','Ă' => 'A','Ç' => 'C','Ć' => 'C',
		'Č' => 'C','Ĉ' => 'C','Ċ' => 'C','Ď' => 'D','Đ' => 'D','È' => 'E',
		'É' => 'E','Ê' => 'E','Ë' => 'E','Ē' => 'E','Ę' => 'E','Ě' => 'E',
		'Ĕ' => 'E','Ė' => 'E','Ĝ' => 'G','Ğ' => 'G','Ġ' => 'G','Ģ' => 'G',
		'Ĥ' => 'H','Ħ' => 'H','Ì' => 'I','Í' => 'I','Î' => 'I','Ï' => 'I',
		'Ī' => 'I','Ĩ' => 'I','Ĭ' => 'I','Į' => 'I','İ' => 'I','Ĵ' => 'J',
		'Ķ' => 'K','Ľ' => 'K','Ĺ' => 'K','Ļ' => 'K','Ŀ' => 'K','Ł' => 'L',
		'Ñ' => 'N','Ń' => 'N','Ň' => 'N','Ņ' => 'N','Ŋ' => 'N','Ò' => 'O',
		'Ó' => 'O','Ô' => 'O','Õ' => 'O','Ø' => 'O','Ō' => 'O','Ő' => 'O',
		'Ŏ' => 'O','Ŕ' => 'R','Ř' => 'R','Ŗ' => 'R','Ś' => 'S','Ş' => 'S',
		'Ŝ' => 'S','Ș' => 'S','Š' => 'S','Ť' => 'T','Ţ' => 'T','Ŧ' => 'T',
		'Ț' => 'T','Ù' => 'U','Ú' => 'U','Û' => 'U','Ū' => 'U','Ů' => 'U',
		'Ű' => 'U','Ŭ' => 'U','Ũ' => 'U','Ų' => 'U','Ŵ' => 'W','Ŷ' => 'Y',
		'Ÿ' => 'Y','Ý' => 'Y','Ź' => 'Z','Ż' => 'Z','Ž' => 'Z','à' => 'a',
		'á' => 'a','â' => 'a','ã' => 'a','ā' => 'a','ą' => 'a','ă' => 'a',
		'å' => 'a','ç' => 'c','ć' => 'c','č' => 'c','ĉ' => 'c','ċ' => 'c',
		'ď' => 'd','đ' => 'd','è' => 'e','é' => 'e','ê' => 'e','ë' => 'e',
		'ē' => 'e','ę' => 'e','ě' => 'e','ĕ' => 'e','ė' => 'e','ƒ' => 'f',
		'ĝ' => 'g','ğ' => 'g','ġ' => 'g','ģ' => 'g','ĥ' => 'h','ħ' => 'h',
		'ì' => 'i','í' => 'i','î' => 'i','ï' => 'i','ī' => 'i','ĩ' => 'i',
		'ĭ' => 'i','į' => 'i','ı' => 'i','ĵ' => 'j','ķ' => 'k','ĸ' => 'k',
		'ł' => 'l','ľ' => 'l','ĺ' => 'l','ļ' => 'l','ŀ' => 'l','ñ' => 'n',
		'ń' => 'n','ň' => 'n','ņ' => 'n','ŉ' => 'n','ŋ' => 'n','ò' => 'o',
		'ó' => 'o','ô' => 'o','õ' => 'o','ø' => 'o','ō' => 'o','ő' => 'o',
		'ŏ' => 'o','ŕ' => 'r','ř' => 'r','ŗ' => 'r','ś' => 's','š' => 's',
		'ť' => 't','ù' => 'u','ú' => 'u','û' => 'u','ū' => 'u','ů' => 'u',
		'ű' => 'u','ŭ' => 'u','ũ' => 'u','ų' => 'u','ŵ' => 'w','ÿ' => 'y',
		'ý' => 'y','ŷ' => 'y','ż' => 'z','ź' => 'z','ž' => 'z','Α' => 'A',
		'Ά' => 'A','Ἀ' => 'A','Ἁ' => 'A','Ἂ' => 'A','Ἃ' => 'A','Ἄ' => 'A',
		'Ἅ' => 'A','Ἆ' => 'A','Ἇ' => 'A','ᾈ' => 'A','ᾉ' => 'A','ᾊ' => 'A',
		'ᾋ' => 'A','ᾌ' => 'A','ᾍ' => 'A','ᾎ' => 'A','ᾏ' => 'A','Ᾰ' => 'A',
		'Ᾱ' => 'A','Ὰ' => 'A','ᾼ' => 'A','Β' => 'B','Γ' => 'G','Δ' => 'D',
		'Ε' => 'E','Έ' => 'E','Ἐ' => 'E','Ἑ' => 'E','Ἒ' => 'E','Ἓ' => 'E',
		'Ἔ' => 'E','Ἕ' => 'E','Ὲ' => 'E','Ζ' => 'Z','Η' => 'I','Ή' => 'I',
		'Ἠ' => 'I','Ἡ' => 'I','Ἢ' => 'I','Ἣ' => 'I','Ἤ' => 'I','Ἥ' => 'I',
		'Ἦ' => 'I','Ἧ' => 'I','ᾘ' => 'I','ᾙ' => 'I','ᾚ' => 'I','ᾛ' => 'I',
		'ᾜ' => 'I','ᾝ' => 'I','ᾞ' => 'I','ᾟ' => 'I','Ὴ' => 'I','ῌ' => 'I',
		'Θ' => 'T','Ι' => 'I','Ί' => 'I','Ϊ' => 'I','Ἰ' => 'I','Ἱ' => 'I',
		'Ἲ' => 'I','Ἳ' => 'I','Ἴ' => 'I','Ἵ' => 'I','Ἶ' => 'I','Ἷ' => 'I',
		'Ῐ' => 'I','Ῑ' => 'I','Ὶ' => 'I','Κ' => 'K','Λ' => 'L','Μ' => 'M',
		'Ν' => 'N','Ξ' => 'K','Ο' => 'O','Ό' => 'O','Ὀ' => 'O','Ὁ' => 'O',
		'Ὂ' => 'O','Ὃ' => 'O','Ὄ' => 'O','Ὅ' => 'O','Ὸ' => 'O','Π' => 'P',
		'Ρ' => 'R','Ῥ' => 'R','Σ' => 'S','Τ' => 'T','Υ' => 'Y','Ύ' => 'Y',
		'Ϋ' => 'Y','Ὑ' => 'Y','Ὓ' => 'Y','Ὕ' => 'Y','Ὗ' => 'Y','Ῠ' => 'Y',
		'Ῡ' => 'Y','Ὺ' => 'Y','Φ' => 'F','Χ' => 'X','Ψ' => 'P','Ω' => 'O',
		'Ώ' => 'O','Ὠ' => 'O','Ὡ' => 'O','Ὢ' => 'O','Ὣ' => 'O','Ὤ' => 'O',
		'Ὥ' => 'O','Ὦ' => 'O','Ὧ' => 'O','ᾨ' => 'O','ᾩ' => 'O','ᾪ' => 'O',
		'ᾫ' => 'O','ᾬ' => 'O','ᾭ' => 'O','ᾮ' => 'O','ᾯ' => 'O','Ὼ' => 'O',
		'ῼ' => 'O','α' => 'a','ά' => 'a','ἀ' => 'a','ἁ' => 'a','ἂ' => 'a',
		'ἃ' => 'a','ἄ' => 'a','ἅ' => 'a','ἆ' => 'a','ἇ' => 'a','ᾀ' => 'a',
		'ᾁ' => 'a','ᾂ' => 'a','ᾃ' => 'a','ᾄ' => 'a','ᾅ' => 'a','ᾆ' => 'a',
		'ᾇ' => 'a','ὰ' => 'a','ᾰ' => 'a','ᾱ' => 'a','ᾲ' => 'a','ᾳ' => 'a',
		'ᾴ' => 'a','ᾶ' => 'a','ᾷ' => 'a','β' => 'b','γ' => 'g','δ' => 'd',
		'ε' => 'e','έ' => 'e','ἐ' => 'e','ἑ' => 'e','ἒ' => 'e','ἓ' => 'e',
		'ἔ' => 'e','ἕ' => 'e','ὲ' => 'e','ζ' => 'z','η' => 'i','ή' => 'i',
		'ἠ' => 'i','ἡ' => 'i','ἢ' => 'i','ἣ' => 'i','ἤ' => 'i','ἥ' => 'i',
		'ἦ' => 'i','ἧ' => 'i','ᾐ' => 'i','ᾑ' => 'i','ᾒ' => 'i','ᾓ' => 'i',
		'ᾔ' => 'i','ᾕ' => 'i','ᾖ' => 'i','ᾗ' => 'i','ὴ' => 'i','ῂ' => 'i',
		'ῃ' => 'i','ῄ' => 'i','ῆ' => 'i','ῇ' => 'i','θ' => 't','ι' => 'i',
		'ί' => 'i','ϊ' => 'i','ΐ' => 'i','ἰ' => 'i','ἱ' => 'i','ἲ' => 'i',
		'ἳ' => 'i','ἴ' => 'i','ἵ' => 'i','ἶ' => 'i','ἷ' => 'i','ὶ' => 'i',
		'ῐ' => 'i','ῑ' => 'i','ῒ' => 'i','ῖ' => 'i','ῗ' => 'i','κ' => 'k',
		'λ' => 'l','μ' => 'm','ν' => 'n','ξ' => 'k','ο' => 'o','ό' => 'o',
		'ὀ' => 'o','ὁ' => 'o','ὂ' => 'o','ὃ' => 'o','ὄ' => 'o','ὅ' => 'o',
		'ὸ' => 'o','π' => 'p','ρ' => 'r','ῤ' => 'r','ῥ' => 'r','σ' => 's',
		'ς' => 's','τ' => 't','υ' => 'y','ύ' => 'y','ϋ' => 'y','ΰ' => 'y',
		'ὐ' => 'y','ὑ' => 'y','ὒ' => 'y','ὓ' => 'y','ὔ' => 'y','ὕ' => 'y',
		'ὖ' => 'y','ὗ' => 'y','ὺ' => 'y','ῠ' => 'y','ῡ' => 'y','ῢ' => 'y',
		'ῦ' => 'y','ῧ' => 'y','φ' => 'f','χ' => 'x','ψ' => 'p','ω' => 'o',
		'ώ' => 'o','ὠ' => 'o','ὡ' => 'o','ὢ' => 'o','ὣ' => 'o','ὤ' => 'o',
		'ὥ' => 'o','ὦ' => 'o','ὧ' => 'o','ᾠ' => 'o','ᾡ' => 'o','ᾢ' => 'o',
		'ᾣ' => 'o','ᾤ' => 'o','ᾥ' => 'o','ᾦ' => 'o','ᾧ' => 'o','ὼ' => 'o',
		'ῲ' => 'o','ῳ' => 'o','ῴ' => 'o','ῶ' => 'o','ῷ' => 'o','А' => 'A',
		'Б' => 'B','В' => 'V','Г' => 'G','Д' => 'D','Е' => 'E','Ё' => 'E',
		'Ж' => 'Z','З' => 'Z','И' => 'I','Й' => 'I','К' => 'K','Л' => 'L',
		'М' => 'M','Н' => 'N','О' => 'O','П' => 'P','Р' => 'R','С' => 'S',
		'Т' => 'T','У' => 'U','Ф' => 'F','Х' => 'K','Ц' => 'T','Ч' => 'C',
		'Ш' => 'S','Щ' => 'S','Ы' => 'Y','Э' => 'E','Ю' => 'Y','Я' => 'Y',
		'а' => 'A','б' => 'B','в' => 'V','г' => 'G','д' => 'D','е' => 'E',
		'ё' => 'E','ж' => 'Z','з' => 'Z','и' => 'I','й' => 'I','к' => 'K',
		'л' => 'L','м' => 'M','н' => 'N','о' => 'O','п' => 'P','р' => 'R',
		'с' => 'S','т' => 'T','у' => 'U','ф' => 'F','х' => 'K','ц' => 'T',
		'ч' => 'C','ш' => 'S','щ' => 'S','ы' => 'Y','э' => 'E','ю' => 'Y',
		'я' => 'Y','ð' => 'd','Ð' => 'D','þ' => 't','Þ' => 'T','ა' => 'a',
		'ბ' => 'b','გ' => 'g','დ' => 'd','ე' => 'e','ვ' => 'v','ზ' => 'z',
		'თ' => 't','ი' => 'i','კ' => 'k','ლ' => 'l','მ' => 'm','ნ' => 'n',
		'ო' => 'o','პ' => 'p','ჟ' => 'z','რ' => 'r','ს' => 's','ტ' => 't',
		'უ' => 'u','ფ' => 'p','ქ' => 'k','ღ' => 'g','ყ' => 'q','შ' => 's',
		'ჩ' => 'c','ც' => 't','ძ' => 'd','წ' => 't','ჭ' => 'c','ხ' => 'k',
		'ჯ' => 'j','ჰ' => 'h'
	);
	$str = str_replace( array_keys( $transliteration ),
	array_values( $transliteration ),	$str);
	return $str;
}
// returns true if $needle is a substring of $haystack
/*
function str_contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}
*/

function eerror_log($str,$file = "")
{
	error_log("E > {$file} : {$str}");
}


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

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

function get_lang_value()
{
	$l = 'en';
	if(isset($_GET['l']) && $_GET['l'] != '')
		$l = $_GET['l'];

	return $l;
}

function get_lang_parameter()
{
	$l = 'en';
	if(isset($_GET['l']) && $_GET['l'] != '')
		$l = $_GET['l'];

	echo "l={$l}";
}
/*
if(isset($_GET['l']) && $_GET['l'] != '')
{
	if(file_exists(__DIR__."/lang/{$_GET['l']}.php"))
	{
		include __DIR__."/lang/{$_GET['l']}.php";
	}else
	{
		include __DIR__."/lang/en.php";
	}
}else {
	include __DIR__."/lang/en.php";
}
*/


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;
	}
}


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

		$_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(print_r($_SESSION,true));
	}

}


// eoDACS functions
function get_number_of_modality(){
 	$nmodality = 0;
	$conn = get_dbconnection();
	$sql = "select row_number() over (order by installation,mod_id) as nbrmod,mod_id from modality where removed = false and active = true order by nbrmod desc limit 1;";
	if ($query = pg_query($conn,$sql)){
		if($row = pg_fetch_row($query)){
				$nmodality = $row[0];
		}
	}
	return $nmodality;
};




function get_full_fdw_request(&$conn, &$sqlarray,&$sessionGLOBALS)
{

  $dblink_type = '';

  if(count($sqlarray) >1 || !array_key_exists(0, $sqlarray))
  {
    //get local request for column name/type
    $first_value  = reset($sqlarray);
    $dblink_type = get_dblink_typeof($conn,$first_value[0]);
  }

  $sqllist = array();
  foreach ($sqlarray as $key => $value)
  {
    if($key == 0)
    {
     $sqllist[] = implode("
      union all
       ", $value);
    }else{
      $tmp = pg_escape_string($conn,implode("
       union all
        ", $value));
        $dblinkconnection = $sessionGLOBALS['eoDACS_FDW'][$key]['dblinkconnectionname'];
      $sqllist[] = "select * from dblink('{$dblinkconnection}','{$tmp}') fdw_{$key}({$dblink_type})";
    }
  }

  $sql = implode("
  union all
   ", $sqllist);


   return $sql;
}


function get_active_remote_site(&$conn)
{

	$sessionGLOBALS = array();
	$sessionGLOBALS['eoDACS_FDW'] = $GLOBALS['eoDACS_FDW'];

	foreach ($sessionGLOBALS['eoDACS_FDW'] as $key => $fdw_site ) {
		if($key == '0' ||  $fdw_site['online'] == false)
			continue;

		if(!pg_query($conn,"select dblink_connect('{$fdw_site['dblinkconnectionname']}','{$fdw_site['servername']}')"))
		{
			error_log("Connection KO = ". $fdw_site['dblinkconnectionname']);
			$sessionGLOBALS['eoDACS_FDW'][$key]['online'] = false;
		}
	}
	$sessionGLOBALS['eoDACS_FDW'] = array_filter($sessionGLOBALS['eoDACS_FDW'], function($var){ return $var['online'];});
	return $sessionGLOBALS;
}

function get_patidlist_by_site(&$conn,&$sessionGLOBALS,$idsite,$pat_id,$stu_id)
{
	if($pat_id != -1)
	{
		$sql = "select id,his_id,birthdate from patient,institution where pat_id = {$pat_id} and institution.inst_id = patient.inst_id;";
	}else{
		$fdw_site = $sessionGLOBALS['eoDACS_FDW'][$idsite];
		$sql = "select id,his_id,birthdate from {$fdw_site['schemaremote']}.patient,{$fdw_site['schemaremote']}.institution,{$fdw_site['schemaremote']}.study where study.stu_id = {$stu_id} and patient.pat_id = study.pat_id and institution.inst_id = patient.inst_id";
	}

	$sqlarray = array();
	$sqlarray[$idsite] = array();
	$sqlarray[$idsite][] = $sql;
	$sql = get_full_fdw_request($conn,$sqlarray,$sessionGLOBALS);
	$patient_ID = '';
	$patient_HIS='';
	$patient_bd='';

	if($query=pg_query($conn,$sql))
	{
		if($row = pg_fetch_row($query))
		{
			$patient_ID = pg_escape_string($conn,$row[0]);
			$patient_HIS = $row[1];
			$patient_bd = $row[2];
		}
	}

	//fetch pat_id from each remote site
	$arr_patid_by_site= array();

	$sqlarray = array();
	foreach ($sessionGLOBALS['eoDACS_FDW'] as $key => &$site ) {
		if(!array_key_exists($key, $sqlarray))
			$sqlarray[$key] = array();

		$sqlarray[$key][] = "select '{$key}',pat_id from {$site["schemaremote"]}.patient,{$site["schemaremote"]}.institution where patient.inst_id = institution.inst_id and id = '{$patient_ID}' and his_id = {$patient_HIS} and birthdate='{$patient_bd}'";
	}

	$sql = get_full_fdw_request($conn,$sqlarray,$sessionGLOBALS);
	if($query=pg_query($conn,$sql))
	{
		while($row = pg_fetch_row($query))
		{
			if(!array_key_exists($row[0],$arr_patid_by_site))
			{
				$arr_patid_by_site[$row[0]] = array(); //push pat_id
			}
			array_push($arr_patid_by_site[$row[0]],$row[1]);
		}
	}

	return $arr_patid_by_site;
}


function get_filecontent($path)
{
	error_log('oo get_filecontent');
  global $config_servernameorip,$EODACS_ROOT;

  $opts = array('http' => array('header'=> 'Cookie: ' . session_name().'='.session_id()."\r\n"));

  $ret = '';
  //commandes
  $url = $config_servernameorip.$EODACS_ROOT.$path;

	if(isset($_SERVER['HTTPS']))
  {
   $arrContextOptions=array(
        "ssl"=>array(
              "verify_peer"=>false,
              "verify_peer_name"=>false,
          ),
          'http' => array('header'=> 'Cookie: ' . session_name().'='.session_id()."\r\n")
      );
     session_write_close();
     $ret = file_get_contents($url, false, stream_context_create($arrContextOptions));

  }else
  {
  	session_write_close();
  	$ret = file_get_contents($url,false,stream_context_create($opts));
  }
  session_start();
  return $ret;
}


?>


