<?php

function apple_bash_variables_set_to_exec(){
	//function needed by apple to correctly set paths. exit from this function should be used like:
	//	$cmd_share=apple_bash_variables_set_to_exec().' sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals --list-principals resources';
	//  exec($cmd_share, $out,$exit);
	//
	return "export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin
	";
	
}


function APPLE_ICAL_SE_SYNC() {

//function to share events from SE/Procesy5 to Apple CalDavServer 
 // creating resources: locations/resources
 // sharing them to correct groups/owners according to source record policy
 //  
 // at the moment @2014-01-15 working only one way
 //  -TODO update added events 2 way
 //  -TODO verify perms for shared calendar
 //  -TODO add events to localisations/resources also (when they are joined somehow in system PROJECTS-LOCATIONS--Table1,Table2,Table3

/*
 $options = $cal->DoOptionsRequest();
DEBUG_S(-3,'options',$options);

if ( isset($options["PROPFIND"]) ) {
   // Fetch some information about the events in that calendar
   $cal->SetDepth(1);
   $folder_xml = $cal->DoXMLRequest("PROPFIND", '<?xml version="1.0" encoding="utf-8" ?><propfind xmlns="DAV:"><prop><getcontentlength/><getcontenttype/><resourcetype/><getetag/></prop></propfind>' );
 }

DEBUG_S(-3,'folder_xml',$folder_xml);

 $events = $cal->GetEvents("20070101T000000Z","20140201T000000Z");
DEBUG_S(-3,'events',$events);

*/
//die('eof TEST');


	$GMT_OFFSET=3600; //jaka roznica czasu do wprowadzania wydarzen w sekundach TODO w konfigu;
	$_REQUEST['ID']=addslashes($_REQUEST['ID']);


	$sql_tables_arr[]="show tables like 'USERS2_MARKETING'";
	$sql_tables_arr[]="show tables like 'IN7_MK_BAZA_DYSTRYBUCJI'";
	$sql_tables_arr[]="show tables like 'DEVICES'";
	$sql_tables_arr[]="show tables like 'TELBOXES'";

	foreach($sql_tables_arr as $sql_tables) {
		$rt=DB::query($sql_tables);
		//! 1 wyszukanie tabel
		while($t=DB::fetch_array($rt)) {
			if(!strstr($t[0],'_HIST'))
	  		$tbls[]=$t[0];
			
		}
	}

	DEBUG_S(-3,'tabele do przejscia',$tbls,__FILE__,__FUNCTION__,__LINE__);


	echo "APPLE_ICAL_SE_SYNC";
	
	
/*
	//! szukamy ostatniej daty zsynchronizwanego wydarzenia lokalnie
	$sql="select unix_timestamp(max(TIMESTAMP))+".$GMT_OFFSET." as MAX_LEFT from CRM_APPLE_ICAL_SYNC_PGSQL";
	$res_max_left=DB::query($sql); 
	while($h=DB::fetch($res_max_left)) {  $max_ts_left=$h->MAX_LEFT;}
	DEBUG_S(-3,'maxymalna data synchr z lewej MAX_LEFT = '.$max_ts_left,null,__FILE__,__FUNCTION__,__LINE__);
	//! szukamy ostatniej daty dodanego/zsynchronizowanego wydarzenia zdalnie 
	//(calendar_metadata resource_id , created,modified - 2013-05-17 11:09:16.409332	)
    $dbconn = pg_connect("host='/Library/Server/PostgreSQL For Server Services/Socket' port=5432 user=caldav dbname=caldav");
	$psql="select extract( epoch from max(cm.modified))  from calendar_metadata as cm
	   left join calendar_object_revisions as cor on  cor.calendar_resource_id=cm.resource_id 
		where cor.resource_name like '%-ical-sqix-sync%' 
		
	    "	;
	    
	$qry=pg_query($dbconn,$psql);
	$fch = pg_fetch_row($qry); list($max_ts_right)=explode(".",$fch[0]); 


	DEBUG_S(-3,'maxymalna data synchr z prawej MAX_RIGHT = '.$max_ts_right,$psql,__FILE__,__FUNCTION__,__LINE__);	
//	sync_events_from_mac($max_ts_left,$max_ts_right);
		
*/		
		
			$uid='4720124D-5F20-4EAB-B501-4872E33F9A5C'; //is a.binder
			$calendar_type='tasks';
//			$events_in_server_cal=mac_ical_get_events_etag('4720124D-5F20-4EAB-B501-4872E33F9A5C','calendar');
			$events_in_server=mac_ical_get_events_etag($uid,$calendar_type);
			
			//$events_in_server = (object)array_merge((array)$events_in_server_cal, (array)$events_in_server_task);
			DEBUG_S(-3,'All Events in server ',$events_in_server,__FILE__,__FUNCTION__,__LINE__);
			mac_ical_parse_events_detect_what_to_sync($events_in_server,$uid,$calendar_type);

	//! FOREACH $tbls

	foreach($tbls as $table) {
		$sql="describe `".$table."`";
		$res=DB::query($sql);
			    $found_ID=false;
			    $found_L_APPOITMENT_DATE=false;
				$found_L_APPOITMENT_USER=false;
				$found_L_APPOITMENT_PERIOD=false;
				$found_L_APPOITMENT_INFO=false;
				$found_A_RECORD_UPDATE_DATE=false;
	//! 2 sprawdzenie czy sa pola do synchronizacji

	//odczytujemy wszystkie eventy z serwera dla potrzeb synchronizacji
		
		while($h=DB::fetch_array($res)) {
			if($h[0]=='ID') $found_ID=true;
			if($h[0]=='L_APPOITMENT_DATE') $found_L_APPOITMENT_DATE=true;
			if($h[0]=='L_APPOITMENT_USER') $found_L_APPOITMENT_USER=true;
		    if($h[0]=='L_APPOITMENT_PERIOD') $found_L_APPOITMENT_PERIOD=true;
		    if($h[0]=='L_APPOITMENT_INFO') $found_L_APPOITMENT_INFO=true;		    
		    if($h[0]=='A_RECORD_UPDATE_DATE') $found_A_RECORD_UPDATE_DATE=true;		    
		}
	
		if(($found_ID)&&($found_L_APPOITMENT_PERIOD)&&($found_L_APPOITMENT_USER)&&($found_L_APPOITMENT_PERIOD)&&($found_L_APPOITMENT_INFO)&&($found_A_RECORD_UPDATE_DATE)) {
		
			echo "<br>Bede synchronizowac ".$table;
			$sql="select t1.*
			        from `".$table."` as t1
			        left join CRM_APPLE_ICAL_SYNC_PGSQL as cs 
			          on ( cs.LOCAL_TABLE='".$table."'  and cs.LOCAL_ID=t1.ID )
			           where cs.ID is null and
			           t1.L_APPOITMENT_DATE>0 and  ( t1.L_APPOITMENT_USER like '%a.binder%' or t1.L_APPOITMENT_USER like 'xx%crash%' or t1.L_APPOITMENT_USER like 'xx%bzyk%' or t1.L_APPOITMENT_USER like 'xx%moksik%') 		           
			          limit 2;
			      ";
			DEBUG_S(-3,'SQL',$sql,__FILE__,__FUNCTION__,__LINE__);
			$res_rigt=DB::query($sql);
	//! 3 szukamy nowych wydarzen do dodania do kalendarza
			while($ROW_WITH_L_APP=DB::fetch($res_rigt)) {
					insert_new_event_to_mac_ical($ROW_WITH_L_APP,$table);
			}
	//! 4 dodajemy nowe resource do kalendarzy - 
			//patrzymy jakie sa pola w danej tabeli - szukajac specjalnej kolumny L_CALENDAR
			$sql="describe ".$table;
			$res_rigt=DB::query($sql);
			$has_L_CALENDAR=false;
			while($ROW_WITH_L_APP=DB::fetch($res_rigt)) {
					if($ROW_WITH_L_APP->Field=='L_CALENDAR') $has_L_CALENDAR=true;
			}
			if($has_L_CALENDAR) {
				$sql="select t1.*
				        from `".$table."` as t1
				        left join _SYNC_ICAL_RESOURCES as cs 
				          on ( cs.LOCAL_TABLE='".$table."'  and cs.LOCAL_ID=t1.ID )
				           where cs.GUID is null and
				           t1.L_CALENDAR='YES'
				          limit 100;
				      ";
				DEBUG_S(-3,'SQL',$sql,__FILE__,__FUNCTION__,__LINE__);
				$res_rigt=DB::query($sql);
				while($ROW_WITH_L_APP=DB::fetch($res_rigt)) {
						mac_ical_try_create_calendar($ROW_WITH_L_APP,$table);
				}
			}
	//! todo szukamy ostatniej daty aktualizacji rekordu ze wszystkich tabel dla danego usera
	    
	//! todo szukamy date ostatniej aktualizacji eventu u uzytkownika
	
	//! todo szukamy daty ostatniej synchronizacji	
		}
	

	

	
	
	}








}



function mac_ical_try_create_calendar($ROW_WITH_L_APP,$table) {
	//$ROW_WITH_L_APP=DB::fetch(zapytanie sql)
	//$table= nazwa tabeli
	//funkcja ktÄĹra probuje stworzyĂÂ kalendarz w przypadku kiedy tabela posiada kolumny CALENDAR oraz CALENDAR_RESOURCE_ID
	// jezeli nie jest puste CALENDAR_RESOURCE_ID to system probuje je stworzyc i zaktualiozwac informacje o numerze resource ID
	// to ma byc jednorazowa akcja
	if(isset($ROW_WITH_L_APP->L_CALENDAR) ) {
		
		if(($ROW_WITH_L_APP->L_CALENDAR=='YES')) {
			//bedziemy tworzyc nowy resource
			mac_ical_create_resource_bash($ROW_WITH_L_APP,$table);
		}
	}
	
}



function mac_ical_get_long_name($ROW_WITH_L_APP,$table) {
	$name=$ROW_WITH_L_APP->ID;
	if(!empty($ROW_WITH_L_APP->M_DISTRIBUTOR)) $name.="_".substr($ROW_WITH_L_APP->M_DISTRIBUTOR, 0,50);
	if(!empty($ROW_WITH_L_APP->M_DIST_DESC)) $name.="_".substr($ROW_WITH_L_APP->M_DIST_DESC, 0,50);
	if(!empty($ROW_WITH_L_APP->T_DEVICE_TYPE)) $name.="_".substr($ROW_WITH_L_APP->T_DEVICE_TYPE, 0,50);
	if(!empty($ROW_WITH_L_APP->T_DEVICE_INFO)) $name.="_".substr($ROW_WITH_L_APP->T_DEVICE_INFO, 0,50);
	if(!empty($ROW_WITH_L_APP->T_DEVICE_SERIAL)) $name.="_".substr($ROW_WITH_L_APP->T_DEVICE_SERIAL, 0,50);
	if(!empty($ROW_WITH_L_APP->T_PRODUCER)) $name.="_".substr($ROW_WITH_L_APP->T_PRODUCER, 0,50);	
	if(!empty($ROW_WITH_L_APP->T_TELBOX_NAME)) $name.="_".substr($ROW_WITH_L_APP->T_TELBOX_NAME, 0,50);	
	if(!empty($ROW_WITH_L_APP->S_ADDRESS_STREET)) $name.="_".substr($ROW_WITH_L_APP->S_ADDRESS_STREET, 0,50);	
	if(!empty($ROW_WITH_L_APP->S_OTHER_INFO)) $name.="_".substr($ROW_WITH_L_APP->S_OTHER_INFO, 0,50);	
	$name=preg_replace('((?![a-z]|[A-Z]|[0-9]|[\ ]|[_]|[-]).)', '', $name);
	return $name;
}

function mac_ical_get_short_name($ROW_WITH_L_APP,$table) {
	$name=$ROW_WITH_L_APP->ID."_".$table;
	
	return $name;
}


function mac_ical_parse_exit_if_added($exit){
   if(strstr($exit[0],'Added')) DEBUG_S(-3,'successfully added new object to calendar');
   else { DEBUG_S(-3,'error adding to calendar server',$exit,__FILE__,__FUNCTION__,__LINE__);
   die();
   }
	die('cos');
}

function mac_ical_notify_created_obj_db($created_resource_UUID,$resource_type,$table,$ROW_WITH_L_APP) {
	//function to notify DB that record was created
	$sql="insert into _SYNC_ICAL_RESOURCES (ID,LOCAL_TABLE,LOCAL_ID,RES_TYPE,GUID) values ('','".$table."','".$ROW_WITH_L_APP->ID."','".$resource_type."','".$created_resource_UUID."')";
	DEBUG_S(-3,'sql to notify DB ',$sql,__FILE__,__FUNCTION__,__LINE__);
	DB::query($sql);
}

function mac_ical_create_resource_bash($ROW_WITH_L_APP,$table) {
	$resource_name=mac_ical_get_long_name($ROW_WITH_L_APP,$table);
	$resource_short_name=mac_ical_get_short_name($ROW_WITH_L_APP,$table);
	//funkcja zaklada nowy resource w lokalnym kalendarzu za pomoca komend roota calendarservermanage_principals
	if($table=='IN7_MK_BAZA_DYSTRYBUCJI') $resource_type='resources';
	else if($table=='TELBOXES') $resource_type='locations';
	else $resource_type='resources';
	
	
	$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --add ".$resource_type." '".$resource_name."' ".$resource_short_name;	$out="";$exit="";
	//$cmd_share='declare';
//	$cmd_share=apple_bash_variables_set_to_exec().' sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals --list-principals resources';
//	$cmd_share='/Users/plabudda/se-dev-pl/SE/stuff/calendarserver_manage_principals_bridge --list-principals resources';
	exec($cmd_share, $out,$exit);
	DEBUG_S(-3,'share calendar cmd/out/exit',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	 mac_ical_parse_exit_if_added($out);
	 $created_resource_UUID=mac_ical_find_resource_id_by_shortname($resource_short_name,$resource_type);
	 
	  mac_ical_notify_created_obj_db($created_resource_UUID,$resource_type,$table,$ROW_WITH_L_APP);
	  mac_ical_share_resource_bash($created_resource_UUID,$ROW_WITH_L_APP->A_CLASSIFIED,$ROW_WITH_L_APP->A_ADM_COMPANY,$ROW_WITH_L_APP->L_APPOITMENT_USER);


	
	
}


function mac_ical_find_resource_id_by_shortname($shortname,$resource_type) {
	$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --list-principals ".$resource_type." |grep ".$shortname." |awk -F ' ' '{ print \$NF }'" ;
	exec($cmd_share, $out,$exit);
	DEBUG_S(3,'share calendar cmd/out/exit',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	foreach($out as $test) {
		$exit="";$out2="";
		$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --list-principals ".$resource_type." |grep ".$shortname." |grep ".$test ;
		exec($cmd_share, $out2,$exit);
		DEBUG_S(3,'specific search for resource ',array($cmd_share,$out2,$exit),__FILE__,__FUNCTION__,__LINE__);

		if(!empty($out2[0])) return $test;
	}
	DEBUG_S(-3,'error finding resource',array($shortname,$resource_type),__FILE__,__FUNCTION__,__FILE__);
	die();
	
}





function mac_ical_share_resource_bash($resource_id,$group_read,$group_write,$owner) {
	//! sprawdzmy jakie sa powiazane proxy do read
	$admin_uid=get_apple_uid('users',$_SESSION['CONFIG']['CALDAV_USERNAME']); //todo - this should be cached variable
	$owner_uid=get_apple_uid('users',$owner); //todo - this should be cached variable
	$group_read_uid=get_apple_uid('groups',$group_read); //todo - this should be cached variable
	$group_write_uid=get_apple_uid('groups',$group_write); //todo - this should be cached variable

		$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --list-write-proxies ".$resource_id." |awk '{ print \$NF }'" ; 	$out="";$exit="";
		exec($cmd_share, $out,$exit);
		DEBUG_S(-3,'look for read proxies to correct (except admin:'.$admin_uid.', owner:'.$owner_uid.', group_read:'.$group_read_uid.', group_write_uid:'.$group_write_uid.')',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
		// we parse data like this : ( we try tu parse starting from line 3 )
		//   [0] => Read/write proxies for "642_BIALLNET Spz oo_Sprawy zwiazane z przygotowaniem dokumentacji oraz" (resources:642_IN7_MK_BAZA_DYSTRYBUCJI):
        //    [1] => Full name              Record name       UUID
        //    [2] => ---------              -----------       ----
        //    [3] => Arkadiusz Binder       a.binder          4720124D-5F20-4EAB-B501-4872E33F9A5C
        //    [4] => Workgroup              workgroup         AEE3F607-1F5B-4E3A-A3D2-785BC23DA17D
        //    [5] => 
		//
		foreach($out as $i=>$test) {
			if(($i>=3)&&(!empty($test))) {
				
				if(!(in_array($test, array($admin_uid,$owner_uid,$group_write_uid)))) {
					//! We remove write proxy which is not correct
					$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --remove-proxy ".$test." ".$resource_id ; 	$out="";$exit="";
					exec($cmd_share, $out,$exit);
					DEBUG_S(-3,'We remove write proxy which is not correct',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
				}
			}
		}
		
	// similar code from upper lines
	$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --list-read-proxies ".$resource_id." |awk '{ print \$NF }'" ; 	$out="";$exit="";
		exec($cmd_share, $out,$exit);
		DEBUG_S(-3,'look for read proxies to correct (except admin:'.$admin_uid.', owner:'.$owner_uid.', group_read:'.$group_read_uid.', group_write_uid:'.$group_write_uid.')',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
		
		foreach($out as $i=>$test) {
			if(($i>=3)&&(!empty($test))) {
				
				if(!(in_array($test, array($group_read_uid)))) {
					//! We remove read proxy which is not correct
					$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --remove-proxy ".$test." ".$resource_id ; 	$out="";$exit="";
					exec($cmd_share, $out,$exit);
					DEBUG_S(-3,'We remove read proxy which is not correct',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
				}
			}
		}
	
  
	//! we make sharing for read / write ...  owner
	if((!empty($group_read))&&($group_read<>$group_write)) {
		$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --add-read-proxy groups:".$group_read." ".$resource_id; 	$out="";$exit="";
		exec($cmd_share, $out,$exit);
		DEBUG_S(-3,'share calendar for group_read',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	}
	if(!empty($group_write)) {
		$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --add-write-proxy groups:".$group_write." ".$resource_id; 	$out="";$exit="";
		exec($cmd_share, $out,$exit);
		DEBUG_S(-3,'share calendar for group_write',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	}
	if(!empty($owner)) {
		$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals  --add-write-proxy users:".$owner." ".$resource_id; 	$out="";$exit="";
		exec($cmd_share, $out,$exit);
		DEBUG_S(-3,'share calendar for owner',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);
	}

	
	
}



function get_apple_uid($resource_type,$resource_name) {
//	$cmd=apple_bash_variables_set_to_exec()." sudo calendarserver_manage_principals --list-principals ".$resource_type." |awk -F ' ' '{ print \$(NF-1)\" \"\$NF }' |grep ".$resource_name." |awk '{ print \$2 }'";
	$cmd='dscl -q /LDAPv3/127.0.0.1 -read /'.$resource_type.'/'.$resource_name.' GeneratedUID';
	$uid=exec($cmd, $out);
	
	if(empty($uid)) {
	 	$cmd='dscl -q /Local/Default/ -read /'.$resource_type.'/'.$resource_name.' GeneratedUID';
	    $uid=exec($cmd, $out);
		DEBUG_S(3,'Finding dscl in LOCAL cmd/out/found ',array($cmd,$out,$uid),__FILE__,__FUNCTION__,__LINE__);

    }
	//$uid=exec($cmd, $out);
	$uid=str_replace('GeneratedUID: ', '', $uid);

	DEBUG_S(3,'Finding dscl command/out/found ',array($cmd,$out,$uid),__FILE__,__FUNCTION__,__LINE__);

	return $uid;
}



function mac_ical_parse_test_return_added_obj($ret) {
	if(strstr($ret, 'Invalid') || strstr($ret,'Failed')) {
		DEBUG_S(-3,'Error adding object',$ret,__FILE__,__FUNCTION__,__LINE__);
		die();
	} 
	DEBUG_S(-3,'Returnet info from server (OK?) ',$ret,__FILE__,__FUNCTION__,__LINE__);
	return true;
}


function mac_ical_create_url_for_edit_obj($ROW_WITH_APP,$table) {
	//TODO @2014-01 wykryc numer zasobu dla URL do edycji
			$dt_res=DB::query("select ID from CRM_LISTA_ZASOBOW where `DESC`='".$table."' and `TYPE`='TABELA' ");
			while($dt=DB::fetch($dt_res)) {
			  return $_SERVER['SCRIPT_URI']."/index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$dt->ID."#EDIT/".$ROW_WITH_L_APP->ID ;
			}
}

function mac_ical_notify_added_event_to_db($ROW_WITH_L_APP,$table,$resource_name,$icalendar_type,$md5_v,$user_uid){

	$sql="insert into CRM_APPLE_ICAL_SYNC_PGSQL (ID, LOCAL_ID,LOCAL_TABLE,TIMESTAMP,resource_name,resource_id,RESOURCE_TYPE,etag,L_APPOITMENT_USER,user_uid) values
	 ('','".$ROW_WITH_L_APP->ID."','".$table."',now(),".$resource_name.",'',".$icalendar_type.",'".md5($v)."','".$ROW_WITH_L_APP->L_APPOITMENT_USER."','".$user_uid."') ";
	DEBUG_S(-3,"SQL do potw wgrania wydarzenia: ",$sql,__FILE__,__FUNCTION__,__LINE__);
	DB::query($sql);

}


function INIT_TABLE() {
	$sql="CREATE TABLE IF NOT EXISTS `_APPLE_ICAL_SE_SYNC_TIMESTAMP` (
  `TIMESTAMP` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'data do kiedy byly zsynchronizowane eventy'
  )";
   DB::query($sql);	
	
}


function mac_ical_get_events_etag($uid,$calendar_type) {
	INIT_TABLE();
	require_once('stuff/caldav-client.php');
 DEBUG_S(-3,'url',$_SESSION['CONFIG']['CALDAV_URL']);
  $cal = new CalDAVClient( $_SESSION['CONFIG']['CALDAV_URL']."/calendars/__uids__/{$uid}/{$calendar_type}/", $_SESSION['CONFIG']['CALDAV_USERNAME'], $_SESSION['CONFIG']['CALDAV_PASSWORD'], "" );
 $options = $cal->DoOptionsRequest();
DEBUG_S(-3,'options',$options);

	//szukam do kiedy byla ostatnia synchronizacja
	$sql="select max(`TIMESTAMP`) as last_sync_ts from _APPLE_ICAL_SE_SYNC_TIMESTAMP";
	$res=DB::query($sql);
	$last_sync_ts=0;
	while($h=DB::fetch($res)) {
		$last_sync_ts=$h->last_sync_ts;
		
	}

//             <C:getctag />
$xmlC = <<<PROPP
<?xml version="1.0" encoding="utf-8" ?>
<D:propfind xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
    <D:prop>
             <D:displayname />
             <D:resourcetype />
             <D:getlastmodified />
             <D:getetag />
     </D:prop>
</D:propfind>
PROPP;

 //if ( isset($options["PROPFIND"]) ) {
   // Fetch some information about the events in that calendar
   $cal->SetDepth(1);
   $folder_xml = $cal->DoXMLRequest("PROPFIND", $xmlC);
   DEBUG_S(3,'folder_xml',$folder_xml,__FILE__,__FUNCTION__,__LINE__);
// }


/*if ( isset($options["PROPFIND"]) ) {
   // Fetch some information about the events in that calendar
   $cal->SetDepth(1);
/*
   $folder_xml = $cal->DoXMLRequest("PROPFIND", '<?xml version="1.0" encoding="utf-8" ?><propfind xmlns="DAV:"><prop><getcontentlength/><getcontenttype/><resourcetype/><getetag/></prop></propfind>' );

 }
*/
DEBUG_S(-3,'folder_xml',$folder_xml,__FILE__,__FUNCTION__,__LINE__);
 return simplexml_load_string($folder_xml);
	
}


function mac_ical_parse_events_detect_what_to_sync($events_in_server,$uid,$calendar_type) {
	//function to parse events from server to detect what to sync (if etag is differ)
	foreach ($events_in_server->response as $id=>$object) {
		$href=$object->href;
		$getetag=ereg_replace('"','',  $object->propstat->prop->getetag);
		$displayname=$object->propstat->prop->displayname;
		$getlastmodified=$object->propstat->prop->getlastmodified;
		//echo "<hr> objects ".$href." ".$getetag." / ".$displayname;
		if(!empty($href) && !empty($getetag) && !empty($displayname)) {
			$sql="select LOCAL_TABLE,LOCAL_ID ,resource_name , etag , unix_timestamp(TIMESTAMP) as modified  from CRM_APPLE_ICAL_SYNC_PGSQL where resource_name='{$displayname}'";
		//	echo $sql;
			$res=DB::query($sql);
			while ($h=DB::fetch($res)) {
				$modifed_time=strtotime($getlastmodified);
				DEBUG_S(-3,"Znalazlem event zsynchronizowany do weryfikacji czy nie nalezy go zsynchronizowac - etag z serwera ({$getetag}) (getlastmodified={$getlastmodified})rem_modified({$modifed_time}!=loc_mod{$h->modified})",$h,__FILE__,__FUNCTION__,__LINE__);
				
				//print_r($modifed_time);
				$sql_="select unix_timestamp(A_RECORD_UPDATE_DATE) as modified from `{$h->LOCAL_TABLE}` where ID={$h->LOCAL_ID}";
					$res_=DB::query($sql_);
					while($h_=DB::fetch($res_)) {
						echo "<br>Modifieds: ".$modifed_time." (".$getlastmodified."=".date(strtotime($getlastmodified)).") h ".$h->modified." h_:".$h_->modified;
						if($h_->modified>$h->modified) $h->modified=$h_->modified;
					}
					
					//@2014-02-11 cos tu jest zjebane z timestampami z kalendarza - jakby zawyzal
				//if($h->etag<>$getetag) mac_ical_parse_event_to_sync($displayname,$uid,$calendar_type,$modifed_time,$getetag);
				if($h->modified<>$modifed_time) mac_ical_parse_event_to_sync($displayname,$uid,$calendar_type,$modifed_time,$getetag);

			}
		}
	}
	
}

function mac_ical_parse_event_to_sync($event,$uid,$calendar_type,$modifed_time,$getetag){
	echo "<br>!!! - trzeba synchronizowac!!! {$event},{$uid},{$calendar_type}";
	require_once('stuff/caldav-client.php');
    $cal = new CalDAVClient( $_SESSION['CONFIG']['CALDAV_URL']."/calendars/__uids__/{$uid}/{$calendar_type}/{$event}", $_SESSION['CONFIG']['CALDAV_USERNAME'], $_SESSION['CONFIG']['CALDAV_PASSWORD'], "" );
	$folder_xml = $cal->DoGETRequest("");
   DEBUG_S(3,'folder_xml',$folder_xml,__FILE__,__FUNCTION__,__LINE__);


	require_once "stuff/iCalcreator.class.php";
	$config=array();
	$vcalendar = new vcalendar($config );
	$vcalendar->parse( $folder_xml );
	if($calendar_type=='tasks') $vevent=$vcalendar->getComponent( "vtodo" );
	else if($calendar_type=='calendar') 	 $vevent=$vcalendar->getComponent( "vevent" );
	DEBUG_S(-3,"vevent getcomponent",$vevent);
	
	
	//get event from database
	$sql="select ID,LOCAL_ID, LOCAL_TABLE , unix_timestamp(TIMESTAMP) as TIMESTAMP  , RESOURCE_TYPE, etag, L_APPOITMENT_USER , user_uid from CRM_APPLE_ICAL_SYNC_PGSQL where resource_name='{$event}' limit 1 ";
	$res_caisp=DB::query($sql);
		while($h=DB::fetch($res_caisp)) {
				$local_syn=$h;
			$sql="select *,unix_timestamp(A_RECORD_UPDATE_DATE) as TIMESTAMP  from `{$h->LOCAL_TABLE}` where `ID`={$h->LOCAL_ID}";
			$res_lt=DB::query($sql);
			while($h_=DB::fetch($res_lt)) {
				$local_rec=$h_;
			}
		}
	if($local_rec->TIMESTAMP>$modifed_time)	{
		echo "sync from local to CalDav";
	} else if($local_rec->TIMESTAMP<$modifed_time) {
		echo "sync from CalDav to Local";
		if($calendar_type=='tasks') {
		//die('todo');
			$new_L_APPOITMENT_DATE=$vevent->due[value][year]."-".$vevent->due[value][month]."-".$vevent->due[value][day];
			$new_L_APPOITMENT_INFO=mysql_real_escape_string($vevent->summary[value]);
			$hist_L_APPOITMENT_INFO=mysql_real_escape_string($vevent->description[0][value]);
			//todo ? czy to wszystko - moze completed trzeba tez zsynchronizowac w inny sposob?!
		} else DEBUG_S(-3,'538 do stworzenia sposob synchronizacji z Caldav VEVENT',null,__FILE__,__FUNCTION__,__LINE__);
		
		//todo do historycznych tabel trzba zapisac funkcja PIOTR
		$sql_local_upd="update `{$local_syn->LOCAL_TABLE}` set `L_APPOITMENT_DATE`='{$new_L_APPOITMENT_DATE}' , `L_APPOITMENT_INFO`='{$new_L_APPOITMENT_INFO}' , A_RECORD_UPDATE_DATE=now() where ID={$local_syn->LOCAL_ID}";
		$sql_local_etag="update CRM_APPLE_ICAL_SYNC_PGSQL set `TIMESTAMP`=from_unixtime({$modifed_time}) where ID={$local_syn->ID} ";

		DEBUG_S(-3,'Lokalnie updatuje dane z serwera CalDav :sql_local_upd/new_L_APPOITMENT_DATE/new_L_APPOITMENT_INFO/hist_L_APPOITMENT_INFO',array($sql_local_upd,$sql_local_etag,$new_L_APPOITMENT_DATE,$new_L_APPOITMENT_INFO,$hist_L_APPOITMENT_INFO),__FILE__,__FUNCTION__,__LINE__);
		DB::query($sql_local_upd);
		DB::query($sql_local_etag);		

	}
	
}


function insert_new_event_to_mac_ical($ROW_WITH_L_APP,$table) {
	DEBUG_S(-3,'f. insert_new_event_to_mac_ical dla tabeli '.$table,$ROW_WITH_L_APP,__FILE__,__FUNCTION__,__LINE__);
               
	$GMT_OFFSET=3600; //jaka roznica czasu do wprowadzania wydarzen w sekundach TODO w konfigu;
	$user_uid=exec('dscl -q /LDAPv3/127.0.0.1 -read /Users/'.$ROW_WITH_L_APP->L_APPOITMENT_USER.' GeneratedUID', $out);
	//$uniqid=uniqid();

	$user_uid=str_replace('GeneratedUID: ', '', $user_uid);
   echo "tutaj".$user_uid;
	if(!empty($user_uid))  {
	
	
	
	require_once "stuff/iCalcreator.class.php";
	$config    = array( "unique_id" => "ical-sqix-sync",
                    "TZID" => "Europe/Warsaw"
                    );
//                   , "TZNAME"  => "CEST" 

	$vcalendar = new vcalendar( $config );
	$config    = $vcalendar->getConfig();

$tz = "Europe/Warsaw";
$xprops = array( "X-LIC-LOCATION" => $tz );
iCalUtilityFunctions::createTimezone( $vcalendar, $tz, $xprops );


	$attachments_mode=0;
	
    $organizer="''";
    $organizer_object='null';
	$recurrance_min='null';
	$recurrance_max='null';
	$access=0;
	$schedule_object='FALSE';
	$schedule_tag="''";
	$schedule_etags="''";
	$private_comments='FALSE';
	$created="LOCALTIMESTAMP";
	$modified="LOCALTIMESTAMP";



	                    
        	echo "<br>".$ROW_WITH_L_APP->L_APPOITMENT_DATE." - to <br>";
			$date_parse=str_replace(array('_',':',' '),'-',$ROW_WITH_L_APP->L_APPOITMENT_DATE);
			$date_parse=explode('-',$ROW_WITH_L_APP->L_APPOITMENT_DATE);
		   DEBUG_S(-3,'exploded L_APPOITMENT_DATE',$date_parse,__FILE__,__FUNCTION__,__LINE__);

			foreach($date_parse as $id=>$val) {
				settype($date_parse[$id], "integer");
			}
			settype($ROW_WITH_L_APP->L_APPOITMENT_PERIOD,"integer");
			//print_r($date_parse);
			$date_YEAR = $date_parse[0];
			$date_MONTH = $date_parse[1];
			$date_DAY = $date_parse[2];
			$date_HOUR = $date_parse[3];
			$date_MIN = $date_parse[4];



echo "<hr>time";
$start_date="'".date('Y-m-d H:i:s',strtotime($date_YEAR."-".$date_MONTH."-".$date_DAY." ".$date_HOUR.":".$date_MIN))."'";
  $end_date="'".date('Y-m-d H:i:s',strtotime($date_YEAR."-".$date_MONTH."-".$date_DAY." ".$date_HOUR.":".$date_MIN)+60*$ROW_WITH_L_APP->L_APPOITMENT_PERIOD)."'";


			$description="Import zadan z systemu Procesy5 z ";//tabeli ".$table." dla rekordu";
			$fields_desc=array('ID','P_ID','K_OD_KOGO','K_ZAWARTOSC','ID_PROJECT','M_DIST_DESC','M_DISTRIBUTOR','S_ADDRESS_CITY','A_PROBLEM_DESC','A_PROBLEM','A_PROBLEM_DATE','A_STATUS','T_TELBOX_ADDRESS','P_NAME','P_PHONE','P_OTHER_INFO','T_TELBOX_BUILDING_IN','I_OPER','S_KLATKA','A_RECORD_UPDATE_AUTHOR' );
			foreach($fields_desc as $fld) {
				if(!empty($ROW_WITH_L_APP->$fld)) $description.="
				[".$fld."] = ".$ROW_WITH_L_APP->$fld;
			}
			$url=mac_ical_create_url_for_edit_obj($ROW_WITH_APP,$table);
			if(!empty($url)) $description.="\n ".$url ;

			

			//unset($date_HOUR);unset($date_MIN);
			if(!empty($date_HOUR)) {
			 ///to bedzie EVENT
			  $calendar_resource_name="calendar";
			 // $config    = $vcalendar->getConfig();

//		  	  $vevent    = new vevent( $vcalendar->getConfig() );
			  $vevent    = & $vcalendar->newComponent( "vevent" );

			  $icalendar_type="'VEVENT'";

		      $vevent->setProperty( "DTSTART",array('year'=>$date_YEAR,'month'=>$date_MONTH,'day'=>$date_DAY,'hour'=>$date_HOUR,'minute'=>$date_MIN,'second'=>0));
     		  $vevent->setProperty( "duration", array("min"=>$ROW_WITH_L_APP->L_APPOITMENT_PERIOD) );
			  $vevent->setProperty( "CALSCALE", "GREGORIAN" );
      		  $vevent->setProperty( "summary", "(P5)".$ROW_WITH_L_APP->L_APPOITMENT_INFO." ".$ROW_WITH_L_APP->L_APPOITMENT_TYPE);
	          $vevent->setProperty( "description", $description);

//			  $vcalendar->setComponent( $vevent );

		  	  $fbtype="(select id from free_busy_type where description='busy')";
			} else {
			  //echo "<hr>bedzie VTODO";
			  $calendar_resource_name="tasks";
			  $fbtype="(select id from free_busy_type where description='free')";
			  $vevent     = & $vcalendar->newComponent( "vtodo" );
			  $vevent->setProperty( "due",array('year'=>$date_YEAR,'month'=>$date_MONTH,'day'=>$date_DAY,'hour'=>$date_HOUR,'minute'=>$date_MIN,'second'=>0));
			  $vevent->setProperty( "dtstart",array('year'=>$date_YEAR,'month'=>$date_MONTH,'day'=>$date_DAY));
			  $vevent->setProperty( "CALSCALE", "GREGORIAN" );
			  $vevent->setProperty( "summary", "(P5)".$ROW_WITH_L_APP->L_APPOITMENT_INFO." ".$ROW_WITH_L_APP->L_APPOITMENT_TYPE );
		      $vevent->setProperty( "description", $description);

			  $icalendar_type="'VTODO'";

			}

//		$vcalendar->setProperty( "TZID", "Europe/Warsaw");
//		$vcalendar->setProperty( "TZOFFSETFROM", '0100');
//		$vcalendar->setProperty( "TZOFFSETTO", '0100');

			if(!empty($url)) $vevent->setProperty( "url", $_SERVER['SCRIPT_URI']."/index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=".$dt->ID."#EDIT/".$ROW_WITH_L_APP->ID );

			if(empty($date_YEAR)) return ; 
		//echo "*".$date_MONTH."*";
		//var_dump($date_MONTH);

		var_dump($date_MONTH);
    
		$uniqid_ind=$vcalendar->getProperty( 'uid' );	
		$uniqid=key($uniqid_ind);
		$vcalendar->parse();
		
		DEBUG_S(-3,'uniqid',$uniqid);
	//	var_dump($uniqid);		
   	$dropbox_id="'".$uniqid.".dropbox'";
	$resource_name="'".$uniqid.".ics'";
	$icalendar_uid="'".$uniqid."'"; 
                    
	
//		$vevent->setProperty( "LOCATION", "Central Plaza" );
		
		
	
		
		//$v=4;
		//var_dump($v);
                                      	



		//echo "<br>Return cal<br>";
		//echo "<br><pre>";

		$v=$vcalendar->createCalendar();
DEBUG_S(-3,'v',$v,__FILE__,__FUNCTION__,__LINE__);
//DEBUG_S(-3,'SERVER',$_SERVER,__FILE__,__FUNCTION__,__LINE__);


/*
$uid = "event-12345";
$v="BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//ical-sqix-sync//NONSGML kigkonsult.se iCalcreator 2.16.12//
BEGIN:VEVENT
DTSTAMP:20140103T130527Z
DTSTART:20140104T130000Z
DTEND:20140104T140000Z
UID:{$uid}
DESCRIPTION:Import zadan z systemu Procesy5 z
LOCATION:Office
SUMMARY:test kalendarza 7 RELATE
END:VEVENT
END:VCALENDAR";
		echo $v;
*/
//		$v=$vcalendar->createCalendar();

		$icalendar_text="'".$v."'";

   		$md5="'".md5($v)."'";

		//echo "</pre>";

/*
Plan taki do synchronizacji kalendarzy


     [ baza translate ] 
	[ LOCAL_ID ]
	[ LOCAL_TABLE ] 
	[ TIMESTAMP ] 
	[ REMOTE_ID ] 
	[ REMOTE_TABLE ] 


1) lokalnie ( dodaje nowe wydarzenie USERS2_MARKETING ( 
   id, 
   data+czas, 
   L_APP_INFO ,
   L_APP_USER)

2) foreach table, ktore maja cos w L_APP_DATE szukam w translate
   a) jak pusto, to 
     - dodaje do  ICALÄËĂÂĂÂa ( REMOTE_TABLE, REMOTE_ID ) 
     - dodaje do [TRANSLATE] [REMOTE_ID,REMOTE_TABLE,LOCAL_ID,LOCAL_TABLE,TIMESTAMP]

    c) trzeba wykryc resource_id -> calendar_home_resource_id  w calendar_home ( po owner_uid  ) 
    b) trzeba wykryc calendar_home_resource_id w calendar_bind
    c) trzeba wykryc w calendar_bind calendar_resource_id (zawsze calendar), 
    (itd...)
 
 4) synchronizacja od strony lokalnej - jezeli rekord LOCAL i A_UPD_DAT jest >  CRM_APPLE_ICAL_SYNC_PGSQL.Timestamp, to jedziemy
   a) zaktualizuj rekord w caldavie
     aa)- zmiana terminow -> edytuj
     bb)- zmiana wlasciciela -> kopiuj nowy obiekt, stary zaznacz skasowano
   
    
 5) synchronizacja od strony caldav'a
   a) - przesun spotkanie
   b) - skasuj spotkanie - wyrzuc siebie z osoby odpowiedzialnej   
 
 
 




*/




//	include 'webdav/vendor/autoload.php';
//echo 'SabreDAV ', \Sabre\DAV\Version::VERSION, ' is installed.';


require_once('stuff/caldav-client.php');
// $cal = new CalDAVClient( "https://biuro.biall-net.pl/", "a.binder", "xxxx", "" );
  $dav_target=$_SESSION['CONFIG']['CALDAV_URL']."/calendars/__uids__/".$user_uid."/".$calendar_resource_name."/{$uniqid}.ics";
  DEBUG_S(-3,'Dav target',$dav_target,__FILE__,__FUNCTION__,__LINE__);
  $cal = new CalDAVClient( $dav_target, $_SESSION['CONFIG']['CALDAV_USERNAME'], $_SESSION['CONFIG']['CALDAV_PASSWORD'], "" );
//$cal->DoPUTRequest("",$icalendar,"");
	//! udostepnienie kalendarza konta docelowego dla administratora - wymaga echo "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals " >> /etc/sudoers;
	$cmd_share=apple_bash_variables_set_to_exec()." sudo /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals --add-write-proxy=users:".$_SESSION['CONFIG']['CALDAV_USERNAME']." users:".$ROW_WITH_L_APP->L_APPOITMENT_USER; 	$out="";$exit="";
	exec($cmd_share, $out,$exit);
	DEBUG_S(-3,'share calendar cmd/out/exit',array($cmd_share,$out,$exit),__FILE__,__FUNCTION__,__LINE__);

$ret=$cal->DoPUTRequest("",$v,'*');
DEBUG_S(-3,'ret/md5',array($ret,$md5),__FILE__,__FUNCTION__,__LINE__);
mac_ical_parse_test_return_added_obj($ret);


// die();
	echo "<br>".$user_uid;

/*

    $dbconn = pg_connect("host='/Library/Server/PostgreSQL For Server Services/Socket' port=5432 user=caldav dbname=caldav");
    $sql_insert_pgsql="insert into calendar_object ( resource_id , calendar_resource_id , resource_name , icalendar_text, icalendar_uid , 
     	icalendar_type , attachments_mode, dropbox_id, organizer, organizer_object, recurrance_min, recurrance_max, access, schedule_object,
		schedule_tag , schedule_etags , private_comments , md5, created, modified ) 
		
		select  
		 (
		select max(resource_id) as max from calendar_object
		union select max(resource_id) as max from calendar_metadata
		order by max desc
		 limit 1
		 )+1 as resource_id
		 
		, t2.calendar_resource_id , ".$resource_name." , ".$icalendar_text." , ".$icalendar_uid."
		, ".$icalendar_type." , ".$attachments_mode." , ".$dropbox_id." , ".$organizer." , ".$organizer_object." 
		, ".$recurrance_min." ,  ".$recurrance_max." ,  ".$access." , ".$schedule_object." 
		, ".$schedule_tag." , ".$schedule_etags." , ".$private_comments." , ".$md5." , ".$created." , ".$modified."
		
		 from calendar_home as t1
		 join calendar_bind as t2 on  ( t1.resource_id=t2.calendar_home_resource_id and t2.calendar_resource_name=".$calendar_resource_name."  ) 
		 where 
		t1.owner_uid='".$user_uid."'
		;
		SELECT resource_id from calendar_object where resource_name=".$resource_name." LIMIT 1;
		";
	
	echo "<br>".$sql_insert_pgsql;
	$qry=pg_query($dbconn,$sql_insert_pgsql);

	$fch = pg_fetch_row($qry);
	echo "<br>\n Inserted id resource id:";
	print_r($fch);

	 $sql_insert_pgsql="insert into calendar_object_revisions  
	 ( calendar_home_resource_id, calendar_resource_id, calendar_name, resource_name, revision, deleted )
	   
	  select  
		t2.calendar_home_resource_id , t2.calendar_resource_id 
		, NULL 
		,  ".$resource_name." 
		 , ( select max(revision) as max from calendar_object_revisions )+1 as revision
		 , FALSE
		from calendar_home as t1 
		join calendar_bind as t2 on  ( t1.resource_id=t2.calendar_home_resource_id and t2.calendar_resource_name=".$calendar_resource_name."  ) 
		 where 
		t1.owner_uid='".$user_uid."' ";
	 	echo "<br>".$sql_insert_pgsql;
	 	pg_query($dbconn,$sql_insert_pgsql);

	$sql_insert_pgsql="insert into time_range ( calendar_resource_id	, calendar_object_resource_id, floating , start_date, end_date , fbtype	, transparent ) 
		select 	 t2.calendar_resource_id , ".$fch[0]." , FALSE , ".$start_date.",".$end_date." , ".$fbtype." , FALSE
		from calendar_home as t1
		join calendar_bind as t2 on  ( t1.resource_id=t2.calendar_home_resource_id and t2.calendar_resource_name=".$calendar_resource_name."  ) 
		 where 
		t1.owner_uid='".$user_uid."' ";
		echo "<br>".$sql_insert_pgsql;
	 	pg_query($dbconn,$sql_insert_pgsql);
	//aktualizacja info, ze cos zostalo dodane itp
	$sql_insert_pgsql="update calendar_metadata set modified=LOCALTIMESTAMP where
	  resource_id=(select t2.calendar_resource_id from calendar_home as t1 
	      join calendar_bind as t2 on  ( t1.resource_id=t2.calendar_home_resource_id and t2.calendar_resource_name=".$calendar_resource_name."  ) 
		   where t1.owner_uid='".$user_uid."'  )  , supported_components=".$icalendar_type." ";

		echo "<br>".$sql_insert_pgsql;
	 	pg_query($dbconn,$sql_insert_pgsql);
	
*/

	//teraz confirm , ze jest zaimportowane
	mac_ical_notify_added_event_to_db($ROW_WITH_L_APP,$table,$resource_name,$icalendar_type,md5($v),$user_uid);
	//pg_last_oid($res2);
	
 } //not empty 



}





