<?php
/*
This file is part of Thomas Bley's moregroupware webmail2/calendar2/admin2 module. (tb-mgw)

More information:
-----------------

Simple Groupware Solutions Thomas Bley
Fichtenstr. 23
Germany, 85640 Putzbrunn

Contact:
--------

info@simple-groupware.de

http://www.simple-groupware.de


Copyright 2002-2003 Thomas Bley
tb-mgw is distributed under the terms of the GNU General Public License 

tb-mgw is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

tb-mgw is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with tb-mgw; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Init2
// Moregroupware.org


error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

if (isset($_GET["icals"])) {
  $icals = $_GET["icals"];
  store_calendar_cals(serialize($icals));
} else {
  $icals = "";
}

if (!is_array($icals)) {
  if (isset($_SESSION["MGW"]->settings["cal2_icals"]) and $_SESSION["MGW"]->settings["cal2_icals"]!="") {
    $icals = unserialize($_SESSION["MGW"]->settings["cal2_icals"]);
  }
}

if (!is_array($icals) or count($icals)==0) {
  $icals = array($_SESSION["MGW"]->username);
}

if ($myEnv["module"]=="overview") {
  $icals = array_merge(array($_SESSION["MGW"]->username),$_SESSION["MGW"]->groups);
}

$sort_entries = false;
$cal_entries = array();
$_SESSION["calendar2_ical"] = $icals;

if (isset($_SESSION["calendar2_preview"]) and $_SESSION["calendar2_preview"]!="" and file_exists($_SESSION["calendar2_preview"])) {
  if (!in_array($hashmap["preview"],$icals)) $icals[] = $hashmap["preview"];
  $cal_entries2 = preview_from_file($_SESSION["calendar2_preview"],$hashmap["preview"]);
  if (is_array($cal_entries2) and count($cal_entries2)>0) {
    foreach ($cal_entries2 as $tmp_entry) {
	  $prev_entry = $tmp_entry[0];
	  break;
	}
    $getdate=date("Ymd",$prev_entry["start_unixtime"]);

	$unix_time = strtotime2($getdate);
	$tomorrows_date = date( 'Ymd', strtotime2('+1 day',  $unix_time));
	$yesterdays_date = date( 'Ymd', strtotime2('-1 day',  $unix_time));
	$display_date = localizeDate($hashmap["dateFormat_day"], $unix_time);
	
	ereg ('([0-9]{4})([0-9]{2})([0-9]{2})', $getdate, $day_array2);
	$this_day = $day_array2[3]; 
	$this_month = $day_array2[2];
	$this_year = $day_array2[1];
	$this_week = date("W",$unix_time);

	$today_today = date ('Ymd');
	ereg ('([0-9]{4})([0-9]{2})([0-9]{2})', $today_today, $today_array2);
	$today_day = $today_array2[3]; 
	$today_month = $today_array2[2];
	$today_year = $today_array2[1];
	$today_week = date("W");

	$thisday2 = localizeDate($hashmap["dateFormat_week_list"], $unix_time);
    if (isset($_GET["debug"]) and $_SESSION["MGW"]->username=="admin") show_print_r($prev_entry);

	if ($prev_entry["native_uid"]!=0) {
	  $id = $prev_entry["native_uid"];
	  $status = $prev_entry["dstatus"];
	  $from = $_SESSION["calendar2_preview_from"];

      $sql = "select * from mgw_calendar2_ics where id=".(int)$id;
      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      if ($res->RecordCount()==1 and $from!="") {
        $row = $res->FetchRow();
	    if ($row["dnow"]==date("Ymd",$prev_entry["dtstamp_unixtime"])."T".date("His",$prev_entry["dtstamp_unixtime"])) {
	      $members = array_merge(explode(",",$row["dorganizer"]),explode(",",$row["dattendee"]),explode(",",$row["dattendee_non"]),explode(",",$row["doptional"]));
		  if (($status=="tentative" or $status=="confirmed" or $status=="cancelled")) { // in_array($from,$members) and 
		    
		    $row["daccepted"] = explode(",",$row["daccepted"]);
		    $row["ddeclined"] = explode(",",$row["ddeclined"]);
		    $row["dtentative"] = explode(",",$row["dtentative"]);

			if (count($row["daccepted"])>0) foreach ($row["daccepted"] as $key=>$key2) if ($key2==$from) $row["daccepted"][$key]="";
			if (count($row["ddeclined"])>0) foreach ($row["ddeclined"] as $key=>$key2) if ($key2==$from) $row["ddeclined"][$key]="";
			if (count($row["dtentative"])>0) foreach ($row["dtentative"] as $key=>$key2) if ($key2==$from) $row["dtentative"][$key]="";
			
			if ($status=="confirmed") $row["daccepted"][] = $from;
			if ($status=="tentative") $row["dtentative"][] = $from;
			if ($status=="cancelled") $row["ddeclined"][] = $from;
			
			$sql = "UPDATE mgw_calendar2_ics SET daccepted=".$conn->Quote(implode(strip_empty_items($row["daccepted"]),",")).",dtentative=".$conn->Quote(implode(strip_empty_items($row["dtentative"]),",")).",ddeclined=".$conn->Quote(implode(strip_empty_items($row["ddeclined"]),","))." where id=".(int)$id;
	        if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		  }
          echo $hashmap["updated_calendar"]." ... <script>setTimeout(\"window.close()\",3000);</script>";
		  $_SESSION["calendar2_preview"] = "";
		  exit;
		} else {
          echo "<script>alert('".addslashes($hashmap["action_outdated"])."'); window.close();</script>";
		  $_SESSION["calendar2_preview"] = "";
		  exit;
		}
	  } else {
        echo "<script>alert('".addslashes($hashmap["app_removed"])."'); window.close();</script>";
		$_SESSION["calendar2_preview"] = "";
		exit;
	  }
	}
  }
  $cal_entries = $cal_entries2;
  $sort_entries = true;
  
  $_SESSION["calendar2_preview2"] = $_SESSION["calendar2_preview"];
  $_SESSION["calendar2_preview"] = "";
}

if (isset($_SESSION["calendar2_preview2"]) and $_SESSION["calendar2_preview2"]!="" and isset($_GET["action"]) and $_GET["action"]!="") {
  	$ifile = fopen($_SESSION["calendar2_preview2"], "r");
	$content="";
	while (!feof($ifile)) {
	  $content .= fread($ifile,1024);
	}
	fclose($ifile);

  	if ($_GET["action"]=="tentative") {
	  $status = "TENTATIVE";
	  $reply_string = $hashmap["tentative"];
	}
  	if ($_GET["action"]=="accept") {
	  $status = "CONFIRMED";
	  $reply_string = $hashmap["accepted"];
	}
  	if ($_GET["action"]=="decline") {
	  $status = "CANCELLED";
	  $reply_string = $hashmap["declined"];
	}

	if (preg_match("/(status:[A-z]*)/i",$content,$regs)) {
	  $content = str_replace($regs[1],"STATUS:".$status,$content);
	} else {
	  $content = str_replace("END:VEVENT","STATUS:".$status."\nEND:VEVENT",$content);
	}

	$webmail_sendmail_temp_dir = CACHE_FOLDER."../webmail2/sendmail/";
    $handle=opendir($webmail_sendmail_temp_dir);
    while ($file = readdir($handle)) {
	  if (!is_dir($file) and $file!="." and $file!="..") {
        $file1 = strstr($file,session_id());
        if ($file1) {
          if (file_exists($webmail_sendmail_temp_dir.$file)) {
            unlink($webmail_sendmail_temp_dir.$file);
          }
        } 
	  }
    }
    closedir($handle);

    $f_email = fopen(CACHE_FOLDER."../webmail2/sendmail/".session_id()."######meeting.ics","w");
    fwrite($f_email, $content);
    fclose($f_email);

    $cal_entries2 = preview_from_file($_SESSION["calendar2_preview2"],$hashmap["preview"]);

    if (is_array($cal_entries2) and count($cal_entries2)>0) {
	  foreach ($cal_entries2 as $tmp_entry) {
	    $entry = $tmp_entry[0];
	    break;
	  }
      $sql = "select id,c_duser_id from mgw_calendar2_ics where c_duser_id=".(int)$_SESSION["MGW"]->userid." and (id=".(int)$entry["native_uid"]." or dnative_uid=".$conn->Quote($entry["id"]).")";
      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

      $row = $res->FetchRow();
	  $count = $res->RecordCount();
      if ($count>0) {
	    if ($_GET["action"]!="decline" and $entry["dstatus"]!="cancelled") {
		  $accepted = "";
		  $tentative = "";
		  if ($_GET["action"]=="tentative") $tentative = $_SESSION["MGW"]->username;
		    else $accepted = $_SESSION["MGW"]->username;

	      $sql = "UPDATE mgw_calendar2_ics set daccepted=".$conn->Quote($accepted).",dtentative=".$conn->Quote($tentative).",dstart=".$conn->Quote($entry["dstart"]).",dend=".$conn->Quote($entry["dend"]).",dsummary=".$conn->Quote($entry["dsummary"]).",dlocation=".$conn->Quote($entry["dlocation"]).",dhomepage=".$conn->Quote($entry["dhomepage"]).",ddesc=".$conn->Quote($entry["ddesc"]).",drep_freq=".$conn->Quote($entry["drep_freq"]).",drep_days=".$conn->Quote($entry["drep_days"]).",drep_until=".$conn->Quote($entry["drep_until"]).",drep_interval=".(int)$entry["drep_interval"].",drep_count=".(int)$entry["drep_count"].",dclass=".$conn->Quote($entry["dclass"]).",dcategories=".$conn->Quote($entry["dcategories"]).",dsequence=".$conn->Quote($entry["dsequence"]).",drep_exdate=".$conn->Quote($entry["drep_exdate"]).",dorganizer=".$conn->Quote($entry["dorganizer"]).",dattendee=".$conn->Quote($entry["dattendee"]).",dattendee_non=".$conn->Quote($entry["dattendee_non"]).",doptional=".$conn->Quote($entry["doptional"]).",dnow=".$conn->Quote($entry["dtstamp_unixtime"]).",duser_id=".$_SESSION["MGW"]->userid." WHERE c_duser_id=".$_SESSION["MGW"]->userid." and id=".(int)$row["id"];
	      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
		} else {
	      $sql = "DELETE FROM mgw_calendar2_ics WHERE c_duser_id=".$_SESSION["MGW"]->userid." and id=".(int)$row["id"];
	      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
		}
	  } elseif ($_GET["action"]!="decline" and $count==0) {
	    $sdate=getDate(time());
	    $now = $sdate["year"].twodigit($sdate["mon"]).twodigit($sdate["mday"])."T".twodigit($sdate["hours"]).twodigit($sdate["minutes"]).twodigit($sdate["seconds"]);
		$accepted = "";
		$tentative = "";
		if ($_GET["action"]=="tentative") $tentative = $_SESSION["MGW"]->username;
		  else $accepted = $_SESSION["MGW"]->username;

	    $sql = "insert into mgw_calendar2_ics (id,dnative_uid,dstart,dend,dsummary,dlocation,dhomepage,ddesc,drep_freq,drep_days,drep_until,drep_interval,drep_count,dclass,dnow,c_duser_id,duser_id,dcalendar,dcategories,dsequence,drep_exdate,dorganizer,dattendee,dattendee_non,doptional,daccepted,dtentative) values 
	      (".mgw_genID('mgw__seq_calendar2_ics').",".$conn->Quote($entry["native_uid"]==0?$entry["id"]:$entry["native_uid"]).",".$conn->Quote($entry["dstart"]).",".$conn->Quote($entry["dend"]).",".$conn->Quote($entry["dsummary"]).",".$conn->Quote($entry["dlocation"]).",".$conn->Quote($entry["dhomepage"]).",".$conn->Quote($entry["ddesc"]).",".$conn->Quote($entry["drep_freq"]).",".$conn->Quote($entry["drep_days"]).",".$conn->Quote($entry["drep_until"]).",".(int)$entry["drep_interval"].",".(int)$entry["drep_count"].",".$conn->Quote($entry["dclass"]).",".$conn->Quote($now).",".$_SESSION["MGW"]->userid.",".$_SESSION["MGW"]->userid.",".$conn->Quote($_SESSION["MGW"]->username).",".$conn->Quote($entry["dcategories"]).",0,".$conn->Quote($entry["drep_exdate"]).",".$conn->Quote($entry["dorganizer"]).",".$conn->Quote($entry["dattendee"]).",".$conn->Quote($entry["dattendee_non"]).",".$conn->Quote($entry["doptional"]).",".$conn->Quote($accepted).",".$conn->Quote($tentative).")";
	    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
	  }
    }

	if ($entry["dstatus"]!="cancelled") {
	  echo "<script>window.opener.top.rightframe.document.location='../webmail2/sendmail_mapper.php?replyto=".$_SESSION["calendar2_preview_mail"][0]."&account=".$_SESSION["calendar2_preview_mail"][1]."&mbox_id=".$_SESSION["calendar2_preview_mail"][2]."&reply_string=".$reply_string."&".SID."';window.close();</script>";
	} else echo "<script>window.close();</script>";
	$_SESSION["calendar2_preview_mail"] = "";
	$_SESSION["calendar2_preview2"] = "";
	exit;	
}

$query_opts = array();
$query = "";
foreach ($icals as $ical) {
  if ($ical=="birthdays" && isModuleInstalled("contact")) {
    $sql = "select p.companyid,p.birthday,p.firstname,p.lastname,p.id from mgw_contacts as p where p.lastname!='' and p.birthday!='' and (p.ispublic=1 or p.owner=".$_SESSION["MGW"]->userid.")";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
      
    while($row = $res->FetchRow()) {
      if ($row["companyid"]!=0) {
        $sql = "select name1 from mgw_companies where id=".(int)$row["companyid"];
        if(!$res2 = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
        $row2 = $res2->FetchRow();
        $row["name1"] = $row2["name1"];
      } else {
        $row["name1"] = "";
      }
	  $birthday = mktime(0,0,0,substr($row['birthday'],5,2),substr($row['birthday'],8,2));
	  
      $birthday_str1 = $this_year.date("md",$birthday);
      $birthday2 = strtotime2("+1 day",$birthday);
      $birthday_str2 = date("Ymd",$birthday2);

      $company = "";
      if ($row["name1"]!="" and $row["companyid"]!=0) { $company = " (".$row["name1"].")"; }
    
	  $cal_entries[$birthday_str1][] = array(
		"dstart" => $birthday_str1,
		"dend" => $birthday_str2,
        "dsummary" => $hashmap["birthday"].": ".$row["firstname"]." ".$row["lastname"].$company,
        "dclass" => "private",
        "drep_freq" => "yearly",
        "drep_until" => "",
        "drep_count" => 0,
        "drep_interval" => 1,
        "drep_days" => "",
        "drep_exdate" => "",
        "dsequence" => 1,
		"ddesc" => "",
		"dlocation" => "",
        "dcategories" => "Birthday",
        "dcalendar" => "birthdays",
        "c_duser_id" => $_SESSION["MGW"]->userid,
        "duser_id" => 0, // $_SESSION["MGW"]->userid
        "id" => md5($_SERVER["HTTP_HOST"]).$row["id"]
	  );
	  $sort_entries = true;
    }
  } elseif ($ical!="") {
    $ical = urldecode($ical);
	
    if (is_numeric($ical)) $id_string = "root_modules_calendar2_groupcalendars_".(int)get_calendar_id($ical);
	  elseif ($ical[0]=="#") $id_string = "root_modules_calendar2_holidaycalendars_".(int)get_calendar_id($ical);
	  elseif ($ical[0]=="@") $id_string = "root_modules_calendar2_publiccalendars_".(int)get_calendar_id($ical);
	  else $id_string = "root_modules_calendar2_personalcalendars_".(int)get_calendar_id($ical);
	  
    if (queryRights2_bool($id_string."_read")) {
      $sql = "select dlocation from mgw_calendar2_cals where dcalendar=".$conn->Quote($ical);
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
      $row = $res->FetchRow();

	  if ($row["dlocation"]=="" or !strpos($row["dlocation"],"://")>0) {
	  if ($query!="") $query .= " or ";
	    $query .= "dcalendar=".$conn->Quote($ical);
      
	  $viewconfidential = false;
	  if (queryRights2_bool($id_string."_viewconfidential")) $viewconfidential = true;
	  
	  $viewprivate = false;
	  if (queryRights2_bool($id_string."_viewprivate")) $viewprivate = true;
	  
	  $query_opts[$ical] = array($viewconfidential,$viewprivate);
	  } else {
		$cal_entries = array_merge($cal_entries,preview_from_file($row["dlocation"],$ical));
      }
	}
  }
}

if ($query!="") {
      $sql = "select * from mgw_calendar2_ics where ".$query." order by dstart";
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
      
      while($row = $res->FetchRow()) {
	    if ($row["dhomepage"]!="" and !strpos("@".$row["dhomepage"],"://")>0) $row["dhomepage"] = "http://".$row["dhomepage"];

		$row["viewconfidential"] = $query_opts[$row["dcalendar"]][0];
		$row["viewprivate"] = $query_opts[$row["dcalendar"]][1];

        $cal_entries[$row["dstart"]][] = $row;
      }
}

if (count($cal_entries)>0) {
  foreach ($cal_entries as $cal2_entry_num_tmp=>$cal2_entry_tmp) {
    foreach ($cal2_entry_tmp as $cal2_entry_num=>$cal2_entry) {
	  if ($cal2_entry["dclass"]=="confidential" and !has_access($cal2_entry,"read")) {
		// confidential
	    $cal_entries[$cal2_entry_num_tmp][$cal2_entry_num] = array();
	  } elseif ($cal2_entry["dclass"]=="private" and !has_access($cal2_entry,"read")) {
		// private
	    $cal_entries[$cal2_entry_num_tmp][$cal2_entry_num] = array(
		   	"dstart" => $cal2_entry["dstart"],
		   	"dend" => $cal2_entry["dend"],
			"dsummary" => $hashmap["private"],
            "dcalendar" => $cal2_entry["dcalendar"],
            "c_duser_id" => $cal2_entry["c_duser_id"],
            "duser_id" => 0, // $cal2_entry["duser_id"]
			"ddesc" => "",
			"dlocation" => "",
	        "dclass" => "",
	        "dcategories" => "",
	        "drep_freq" => $cal2_entry["drep_freq"],
    	    "drep_until" => $cal2_entry["drep_until"],
        	"drep_count" => $cal2_entry["drep_count"],
	        "drep_interval" => $cal2_entry["drep_interval"],
    	    "drep_days" => $cal2_entry["drep_days"],
        	"drep_exdate" => $cal2_entry["drep_exdate"],
	        "dsequence" => $cal2_entry["dsequence"],
            "id" => $cal2_entry["id"],
	    );
	  }
	}
  }
}


/*
$holidays = array("holidays/JapanHolidays.ics"=>"JapanHolidays","holidays/USHolidays.ics"=>"Holidays_us_03");

foreach ($holidays as $import_cal_filename=>$import_cal_name) {

  $sdate=getDate(time());
  $now = $sdate["year"].twodigit($sdate["mon"]).twodigit($sdate["mday"])."T".twodigit($sdate["hours"]).twodigit($sdate["minutes"]).twodigit($sdate["seconds"]);

  preview_from_file($import_cal_filename,$import_cal_name);

  if (is_array($cal_entries[$import_cal_name]) and count($cal_entries[$import_cal_name])>0) {
    foreach ($cal_entries[$import_cal_name] as $entry) {
      $sql = "insert into mgw_calendar2_ics (id,dstart,dend,dsummary,dlocation,ddesc,drep_freq,drep_days,drep_until,drep_interval,drep_count,dclass,dnow,c_duser_id,duser_id,dcalendar,dcategories,dsequence,drep_exdate) values 
        (".mgw_genID('mgw__seq_calendar2_ics').",".$conn->Quote($entry["dstart"]).",".$conn->Quote($entry["dend"]).",".$conn->Quote($entry["dsummary"]).",".$conn->Quote($entry["dlocation"]).",".$conn->Quote($entry["ddesc"]).",".$conn->Quote($entry["drep_freq"]).",".$conn->Quote($entry["drep_days"]).",".$conn->Quote($entry["drep_until"]).",".(int)$entry["drep_interval"].",".(int)$entry["drep_count"].",".$conn->Quote($entry["dclass"]).",".$conn->Quote($now).",".$_SESSION["MGW"]->userid.",".$_SESSION["MGW"]->userid.",".$conn->Quote($import_cal_name).",".$conn->Quote($entry["dcategories"]).",0,".$conn->Quote($entry["drep_exdate"]).")";
//      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    }
  }
}
*/

if ($sort_entries) ksort($cal_entries);

if (isset($_GET["debug2"])) show_print_r($cal_entries);
// die;

?>