<?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
*/

// Event
// Moregroupware.org

$myEnv["module"] = "calendar2";
$myEnv["stdsmenu"] = false;
$myEnv["output"] = "html";

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(INCLUDEPATH . "mSelectBox.class.php");

include CAL2_INC_DIR."timezones.php";
include (CAL2_INC_DIR.'init.inc.php'); 

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$myvars = array("id","dstart","dend","dsummary","ddesc","dlocation","dhomepage","drep_freq","start_day","start_month","start_year","rep_day","rep_month","rep_year","end_day","end_month","end_year","drep_day_mo","drep_day_tu","drep_day_we","drep_day_th","drep_day_fr","drep_day_sa","drep_day_su","dclass","dentireday","dcalendar","drep_interval","drep_count","delete","calendar_name2","edit_id","dcategories","dforever","dorganizer","dattendee","dattendee_non","doptional");
foreach ($myvars as $thevar) {
  ${$thevar} = (isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "");
  //  echo $thevar." ".${$thevar}."<br>";
}

if ($getdate=="") {	$getdate = date('Ymd'); }

if (!isset($_SESSION["MGW"]->settings["cal2_timezone"]) or $_SESSION["MGW"]->settings["cal2_timezone"] =="") {
  $_SESSION["MGW"]->settings["cal2_timezone"] = 'Same as Server';
}
$timezone = $_SESSION["MGW"]->settings["cal2_timezone"];

if (!isset($_SESSION["MGW"]->settings["cal2_num_years"]) or $_SESSION["MGW"]->settings["cal2_num_years"] =="") {
  $_SESSION["MGW"]->settings["cal2_num_years"] = '3';
}
$num_years = $_SESSION["MGW"]->settings["cal2_num_years"];

if (isset($_SESSION["MGW"]->settings["cal2_start_time"]) and $_SESSION["MGW"]->settings["cal2_start_time"] !="") {
  $day_start = $_SESSION["MGW"]->settings["cal2_start_time"];
} else {
  $day_start = '0900';
}

if (isset($_SESSION["MGW"]->settings["cal2_end_time"]) and $_SESSION["MGW"]->settings["cal2_end_time"] !="") {
  $day_end = $_SESSION["MGW"]->settings["cal2_end_time"];
} else {
  $day_end = '1800';
}

if (isset($_SESSION["MGW"]->settings["cal2_grid_length"]) and $_SESSION["MGW"]->settings["cal2_grid_length"] !="") {
  $gridLength = $_SESSION["MGW"]->settings["cal2_grid_length"];
} else {
  $gridLength = '15';
}

if (isset($_SESSION["MGW"]->settings["cal2_start_week"]) and $_SESSION["MGW"]->settings["cal2_start_week"] !="") {
  $week_start_day = $_SESSION["MGW"]->settings["cal2_start_week"];
} else {
  $week_start_day = 'Monday';
}

if ($dcategories=="") { $dcategories = array(); }
    
$sdate=getDate(time());
    
if ($dend=="" and $dstart!="") { $dend = date("Hi",strtotime2($dstart)+1800); }
if ($start_day !="" and $end_day=="") { $end_day = $start_day; }
if ($start_month !="" and $end_month=="") { $end_month = $start_month; }
if ($start_year !="" and $end_year=="") { $end_year = $start_year; }

if ($start_day !="" and $rep_day=="") { $rep_day = $start_day; }
if ($start_month !="" and $rep_month=="") { $rep_month = $start_month; }
if ($start_year !="" and $rep_year=="") { $rep_year = $start_year; }
    
if ($calendar_name2=="birthdays") {
  echo "<script>window.opener.document.location='../contact/index.php?mod=contact&obj=person&view=details&id=".str_replace(md5($_SERVER["HTTP_HOST"]),"",$edit_id)."&sort=&list=&searchterm=&npage=1&".SID."'; window.close();</script>";
  exit;
}

$close_window = false;
$reload_parent = false;
$redirect_webmail = false;
$access_denied = false;
     
$id2 = "";
     
$cals_users = array();
$cals_groups = array();
$cals_holidays = array();
$cals_others = array();

if ($dsummary != "" and $delete=="") {

  $drep_days = ($drep_day_mo?"mo,":"");
  $drep_days .= ($drep_day_tu?"tu,":"");
  $drep_days .= ($drep_day_we?"we,":"");
  $drep_days .= ($drep_day_th?"th,":"");
  $drep_days .= ($drep_day_fr?"fr,":"");
  $drep_days .= ($drep_day_sa?"sa,":"");
  $drep_days .= ($drep_day_su?"su,":"");
  if ($drep_days) {$drep_days = substr($drep_days,0,strlen($drep_days)-1);}

  $dstart3 = "T".$dstart."00";
  $dend3 = "T".$dend."00";

  if ($dentireday) {
    $dstart3 = ""; $dend3 = "";
    if ($start_day == $end_day) {
	  $end_year = date("Y",strtotime2($start_year.$start_month.$start_day)+(24*3600));
	  $end_month = date("m",strtotime2($start_year.$start_month.$start_day)+(24*3600));
	  $end_day = date("d",strtotime2($start_year.$start_month.$start_day)+(24*3600));
	}
  }
  
  $dstart2 = $start_year.$start_month.$start_day.$dstart3;
  $dend2 = $end_year.$end_month.$end_day.$dend3;

  $now = $sdate["year"].twodigit($sdate["mon"]).twodigit($sdate["mday"])."T".twodigit($sdate["hours"]).twodigit($sdate["minutes"]).twodigit($sdate["seconds"]);
  $drep_until = $rep_year.$rep_month.$rep_day."T000000";
  
  if ($dforever!="") { $drep_until = "forever"; }

  if (!$drep_days and $drep_freq=="weekly") {
	$drep_freq = "none"; $drep_until = ""; $drep_interval = 0; $drep_count = 0;
	$drep_day_mo = ""; $drep_day_tu = ""; $drep_day_we = ""; 
    $drep_day_th = ""; $drep_day_fr = ""; $drep_day_sa = ""; $drep_day_su = "";
    $rep_day=""; $rep_month=""; $rep_year="";
  }
  
  if ($drep_freq=="none") {
	$drep_days = ""; $drep_until = ""; $drep_interval = 0; $drep_count = 0;
    $drep_day_mo = ""; $drep_day_tu = ""; $drep_day_we = ""; 
    $drep_day_th = ""; $drep_day_fr = ""; $drep_day_sa = ""; $drep_day_su = "";
    $rep_day=""; $rep_month=""; $rep_year="";
  }
  if ($dclass=="") {$dclass = "public";}
  
  if ($id=="" and $dcalendar!="") {
	if (get_right_cal2($dcalendar,"create")) {
	  $id2 = mgw_genID('mgw__seq_calendar2_ics');
      $sql = "insert into mgw_calendar2_ics (id,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,dorganizer,dattendee,dattendee_non,doptional,daccepted) values 
        (".$id2.",".$conn->Quote($dstart2).",".$conn->Quote($dend2).",".$conn->Quote($dsummary).",".$conn->Quote($dlocation).",".$conn->Quote($dhomepage).",".$conn->Quote($ddesc).",".$conn->Quote($drep_freq).",".$conn->Quote($drep_days).",".$conn->Quote($drep_until).",".(int)$drep_interval.",".(int)$drep_count.",".$conn->Quote($dclass).",".$conn->Quote($now).",".$_SESSION["MGW"]->userid.",".$_SESSION["MGW"]->userid.",".$conn->Quote($dcalendar).",".$conn->Quote(implode(",",$dcategories)).",0,".$conn->Quote($dorganizer).",".$conn->Quote($dattendee).",".$conn->Quote($dattendee_non).",".$conn->Quote($doptional).",".$conn->Quote($_SESSION["MGW"]->username).")";
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
	} else {
	  $access_denied = true;
	}	  
    $close_window = true;
    $reload_parent = true;
  }

  if ($id!="" and $dcalendar!="") {
    $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) {
      $row = $res->FetchRow();
      $row_dcalendar = $row["dcalendar"];
      $row_dsequence = $row["dsequence"];
	  if (!is_numeric($row_dsequence)) { $row_dsequence = 0; }
	  if (get_right_cal2($row_dcalendar,"modify") and has_access($row)) {
	  
	    if ($row_dcalendar==$dcalendar or (get_right_cal2($dcalendar,"create") and get_right_cal2($row_dcalendar,"delete"))) {
  	      $sql = "update mgw_calendar2_ics set 
			  dcalendar=".$conn->Quote($dcalendar).",
              dstart=".$conn->Quote($dstart2).", dend=".$conn->Quote($dend2).",
              dsummary=".$conn->Quote($dsummary).", dlocation=".$conn->Quote($dlocation).",
			  dhomepage=".$conn->Quote($dhomepage).",
              ddesc=".$conn->Quote($ddesc).", drep_freq=".$conn->Quote($drep_freq).",
              drep_days=".$conn->Quote($drep_days).", drep_until=".$conn->Quote($drep_until).",
              drep_interval=".(int)$drep_interval.", dclass=".$conn->Quote($dclass).",
              dcategories=".$conn->Quote(implode(",",$dcategories)).", drep_count=".(int)$drep_count.", 
              dnow=".$conn->Quote($now).", dsequence=".(int)($row_dsequence+1).",
			  duser_id=".$_SESSION["MGW"]->userid.",
			  dorganizer=".$conn->Quote($dorganizer).",dattendee=".$conn->Quote($dattendee).",
			  dattendee_non=".$conn->Quote($dattendee_non).",doptional=".$conn->Quote($doptional).",
			  daccepted=".$conn->Quote($_SESSION["MGW"]->username).",ddeclined='',dtentative=''
              where id=".(int)$id;
          if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
		} else {
	      $access_denied = true;
		}
	  } else {
	    $access_denied = true;
	  }

      $close_window = true;
      $reload_parent = true;
    }
  }
}

if (($id!="" or $id2!="") and ($dorganizer!="" or $dattendee!="" or $dattendee_non!="" or $doptional!="") and isModuleInstalled("webmail2")) {
  if ($id!="") $id2 = $id;
  $sql = "select * from mgw_calendar2_ics where id=".(int)$id2;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();

  if (isset($row["dcalendar"]) and $row["dcalendar"]!="" and get_right_cal2($row["dcalendar"],"modify") and has_access($row)and $row["dcalendar"]!="") {
  
	$daysofweek_lang			= explode(",",$hashmap["daysofweek_lang"]);
	$daysofweekshort_lang		= explode(",",$hashmap["daysofweekshort_lang"]);
	$daysofweekreallyshort_lang	= explode(",",$hashmap["daysofweekreallyshort_lang"]);
	$monthsofyear_lang			= explode(",",$hashmap["monthsofyear_lang"]);
	$monthsofyearshort_lang		= explode(",",$hashmap["monthsofyearshort_lang"]);

    $event_str = "BEGIN:VEVENT\n"."UID:".md5($_SERVER["HTTP_HOST"]).$row["id"]."\n";
        
    if (strlen($row["dstart"]) > 8 and strlen($row["dend"]) > 8) {
	ereg ('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{0,2})([0-9]{0,2})', $row["dstart"], $regs);
	$start_date = $regs[1] . $regs[2] . $regs[3];
	$start_time = $regs[4] . $regs[5];
	$start_unixtime = mktime($regs[4], $regs[5], 0, $regs[2], $regs[3], $regs[1]);
		
	ereg ('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{0,2})([0-9]{0,2})', $row["dend"], $regs);
	$end_date = $regs[1] . $regs[2] . $regs[3];
	$end_time = $regs[4] . $regs[5];
	$end_unixtime = mktime($regs[4], $regs[5], 0, $regs[2], $regs[3], $regs[1]);

	$start_unixtime = calcTime($tz_array[$_SESSION["MGW"]->settings["cal2_timezone"]][date('I', $start_unixtime)], chooseOffset($start_unixtime), $start_unixtime);
	$end_unixtime = calcTime($tz_array[$_SESSION["MGW"]->settings["cal2_timezone"]][date('I', $end_unixtime)], chooseOffset($end_unixtime), $end_unixtime);
	
      $start_time = $hashmap["event_start_lang"].": ".localizeDate($hashmap["dateFormat_day"]." %Y", $start_unixtime)." ".date($hashmap["timeFormat"],$start_unixtime)."<br>";
	  $end_time = $hashmap["event_end_lang"].": ".localizeDate($hashmap["dateFormat_day"]." %Y", $end_unixtime)." ".date($hashmap["timeFormat"],$end_unixtime)."<br>";
      
      $event_str .= "DTSTAMP:".$row["dnow"]."\nDTSTART;TZID=".$timezone.":".$row["dstart"]."\n"."DTEND;TZID=".$timezone.":".$row["dend"]."\n";
    } else {
	  ereg ('([0-9]{4})([0-9]{2})([0-9]{2})', $row["dstart"], $regs);
	  $start_unixtime = mktime(0, 0, 0, $regs[2], $regs[3], $regs[1]);
		
	  ereg ('([0-9]{4})([0-9]{2})([0-9]{2})', $row["dend"], $regs);
	  $end_unixtime = mktime(0, 0, 0, $regs[2], $regs[3], $regs[1]);

      $start_time = $hashmap["event_start_lang"].": ".localizeDate($hashmap["dateFormat_day"]." %Y", $start_unixtime)."<br>";
	  $end_time = $hashmap["event_end_lang"].": ".localizeDate($hashmap["dateFormat_day"]." %Y", $end_unixtime)."<br>";
      
      $event_str .= "DTSTAMP:".$row["dnow"]."\nDTSTART;VALUE=DATE:".$row["dstart"]."\n"."DTEND;VALUE=DATE:".$row["dend"]."\n";
    }

    $event_str .= "SUMMARY:".$row["dsummary"]."\n";

/*
	$organizer = "";
    if ($row["duser_id"] and is_numeric($row["duser_id"])) {
      $sql = "select firstname,lastname,username,email from mgw_users where id=".(int)$row["duser_id"];
      if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      if ($res2->RecordCount()==1) {
        $row2 = $res2->FetchRow();
        // $row2["email"] = ":MAILTO:".$row2["username"];
        if ($row2["email"]!="") { $row2["email"] = ":MAILTO:".$row2["email"]; }
        $event_str .= "ORGANIZER;CN=\"".$row2["firstname"]." ".$row2["lastname"]."\"".$row2["email"]."\n";
		$organizer = $row2["firstname"]." ".$row2["lastname"];
      }
    }
*/
	if ($row["dorganizer"]!="") $event_str .= make_event_str_participants($row["dorganizer"],"ORGANIZER"); 
	if ($row["dattendee"]!="") $event_str .= make_event_str_participants($row["dattendee"],"ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE");
	if ($row["dattendee_non"]!="") $event_str .= make_event_str_participants($row["dattendee_non"],"ATTENDEE;ROLE=OPT-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE");
	if ($row["doptional"]!="") $event_str .= make_event_str_participants($row["doptional"],"ATTENDEE;ROLE=NON-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE");

	if ($row["dhomepage"]!="" and !strpos("@".$row["dhomepage"],"://")>0) $row["dhomepage"] = "http://".$row["dhomepage"];
    if ($row["dlocation"]) { $event_str .= "LOCATION".($row["dhomepage"]?";ALTREP=\"".$row["dhomepage"]."\"":"").":".$row["dlocation"]."\n"; }
    if ($row["ddesc"]) { $event_str .= "DESCRIPTION:".str_replace(array("\n","\r"),array("<br>",""),$row["ddesc"])."\n"; }
    if ($row["dcategories"] and $row["dcategories"]!="None") { $event_str .= "CATEGORIES:".str_replace("None,","",$row["dcategories"])."\n"; }
    if ($row["dclass"]) { $event_str .= "CLASS:".$row["dclass"]."\n"; }
    if ($row["drep_until"]!="forever") { $rep_until = "UNTIL=".$row["drep_until"].";"; } else { $rep_until = ""; }
  
    if ($row["drep_freq"]=="weekly") { $by_day = ";BYDAY=".strtoupper($row["drep_days"]); }
      elseif ($row["drep_freq"]=="monthly") { $by_day = ";BYMONTHDAY=".(int)substr($row["dstart"],6,2); }
      elseif ($row["drep_freq"]=="yearly") { $by_day = ";BYMONTH=".(int)substr($row["dstart"],4,2); }
      else $by_day = "";
	
    if ($row["drep_count"]!=0 and $row["drep_count"]) { $row["drep_count"]=";COUNT=".$row["drep_count"]; } else { $row["drep_count"] = ""; }
    if ($row["drep_interval"]!=0 and $row["drep_freq"]!="none" and ($row["drep_freq"]!="weekly" or $row["drep_days"])) { $event_str .= "RRULE:FREQ=".strtoupper($row["drep_freq"]).$row["drep_count"].";".$rep_until."INTERVAL=".$row["drep_interval"].$by_day."\n"; }
    if ($row["dsequence"]) { $event_str .= "SEQUENCE:".$row["dsequence"]."\n"; }

    $event_str .= "STATUS:".($delete!=""?"CANCELLED":"CONFIRMED")."\nEND:VEVENT\n\n";

	$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_".$id2.".ics","w");

    $init = "BEGIN:VCALENDAR\nCALSCALE:GREGORIAN\nPRODID:-//more.groupware//Calendar2//EN\nVERSION:2.0\nMETHOD:REQUEST\n";
          
    if (strlen($row["dstart"]) > 8 and strlen($row["dend"]) > 8) {
      if ($tz_array[$timezone][0]!=$tz_array[$timezone][1]) {
        if (!isset($tz_array[$timezone][2])) {
          $tz_array[$timezone][2] = "";
          $tz_array[$timezone][3] = "";
        } else {
          $tz_array[$timezone][2] = "\nRRULE:".$tz_array[$timezone][2];
          $tz_array[$timezone][3] = "\nRRULE:".$tz_array[$timezone][3];
        }
        $init .= "BEGIN:VTIMEZONE\nTZID:".$timezone."\nBEGIN:DAYLIGHT\nTZOFFSETFROM:".$tz_array[$timezone][0]."\nTZOFFSETTO:".$tz_array[$timezone][1]."\nDTSTART:16010101T020000".$tz_array[$timezone][3]."\nEND:DAYLIGHT\nBEGIN:STANDARD\nTZOFFSETFROM:".$tz_array[$timezone][1]."\nTZOFFSETTO:".$tz_array[$timezone][0]."\nDTSTART:16010101T030000".$tz_array[$timezone][2]."\nEND:STANDARD\nEND:VTIMEZONE\n";
      } else {
        $init .= "BEGIN:VTIMEZONE\nTZID:".$timezone."\nBEGIN:STANDARD\nTZOFFSETFROM:".$tz_array[$timezone][1]."\nTZOFFSETTO:".$tz_array[$timezone][0]."\nDTSTART:16010101T030000\nEND:STANDARD\nEND:VTIMEZONE\n";
      }
    }

	$dsummary = $hashmap["appointment"].": ".$row["dsummary"]."<br>";
	
	$organizer = "";
	if ($row["dorganizer"]!="") $organizer = ucfirst($hashmap["calendar_organizer"]).": ".$row["dorganizer"]."<br><br>";
	if ($row["dattendee"]!="") $organizer .= ucfirst($hashmap["calendar_attendee"]).": ".$row["dattendee"]."<br>";
	if ($row["dattendee_non"]!="") $organizer .= ucfirst($hashmap["calendar_attendee_non"]).": ".$row["dattendee_non"]."<br>";
	if ($row["doptional"]!="") $organizer .= ucfirst($hashmap["calendar_optional"]).": ".$row["doptional"]."<br><br>";
	if ($row["dlocation"]!="") $row["dlocation"] = $hashmap["location"].": ".$row["dlocation"]."<br><br>";
	if ($row["dhomepage"]!="") $row["dhomepage"] = $hashmap["homepage"].": <a href='".$row["dhomepage"]."' target='_blank'>".$row["dhomepage"]."</a><br><br>";
	if ($row["ddesc"]!="") $row["ddesc"] = $hashmap["description_lang"].":<br>".$row["ddesc"]."<br>";

    fwrite($f_email, $init.str_replace("\n\n","\n",$event_str)."END:VCALENDAR\n\n");
    fclose($f_email);
    $_SESSION["webmail2_compose_array"]["to"] = $row["dattendee"].($row["dorganizer"]!="" && $row["dattendee"]!=""?", ".$row["dorganizer"]:$row["dorganizer"]);
	$_SESSION["webmail2_compose_array"]["to"] = str_replace(",",", ",trim(str_replace(",".$_SESSION["MGW"]->username.",",",",",".str_replace(" ","",$_SESSION["webmail2_compose_array"]["to"]).","),","));
	
    $_SESSION["webmail2_compose_array"]["cc"] = $row["dattendee_non"].($row["doptional"]!="" && $row["dattendee_non"]?", ".$row["doptional"]:$row["doptional"]);
	$_SESSION["webmail2_compose_array"]["cc"] = str_replace(",",", ",trim(str_replace(",".$_SESSION["MGW"]->username.",",",",",".str_replace(" ","",$_SESSION["webmail2_compose_array"]["cc"]).","),","));

    $_SESSION["webmail2_compose_array"]["subject"] = ($delete!=""?$hashmap["cancelled"].": ":"").$hashmap["appointment"].": ".$row["dsummary"];
	// $dtimezone.
    $_SESSION["webmail2_compose_array"]["msgbody"] = htmlspecialchars($dsummary.$organizer.$start_time.$end_time."<br>".$row["dlocation"].$row["dhomepage"].$row["ddesc"]."<br>*~*~*~*~* <a href='http://www.moregroupware.org' target='_blank'>more.groupware</a> *~*~*~*~*<br><br>");

	if ($_SESSION["webmail2_compose_array"]["to"]!="") $redirect_webmail = true;
  } else {
    $access_denied = true;
  }
  $reload_parent = true;
}

if ($id!="" and $delete!="") {
  $sql = "select * from mgw_calendar2_ics where id='".(int)$id."'";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
      
  $del_cal = "";
  if ($res->RecordCount()==1) {
    $row = $res->FetchRow();
    if ($row["dcalendar"]!="" and get_right_cal2($row["dcalendar"],"delete") and has_access($row)) {
	  $sql = "delete from mgw_calendar2_ics where dcalendar=".$conn->Quote($row["dcalendar"])." and id=".(int)$id;
      if(!$res2 = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    } else {
	  $access_denied = true;
    }
  }
  $close_window = true;
  $reload_parent = true;
}
    
if (is_numeric($edit_id)) {
  $sql = "select * from mgw_calendar2_ics where id=".(int)$edit_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  $row = $res->FetchRow();

  $dcalendar = $row["dcalendar"];
  
  if ($dcalendar!="" and get_right_cal2($dcalendar,"read") and has_access($row)) {
	
	$show_others = get_right_cal2($dcalendar,"delete");

  	$sql = "SELECT dcalendar FROM mgw_calendar2_cals order by dcalendar";
	if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	while($row2 = $res2->FetchRow()) {
	  if ($dcalendar==$row2["dcalendar"] or ($show_others and get_right_cal2($row2["dcalendar"],"create"))) {
        if (is_numeric($row2["dcalendar"])) {
		  $cals_groups[] = array($row2["dcalendar"],get_real_calendar_name($row2["dcalendar"]));
		} elseif ($row2["dcalendar"][0]=="#") {
		  $cals_holidays[] = array($row2["dcalendar"],get_real_calendar_name($row2["dcalendar"]));
		} elseif ($row2["dcalendar"][0]=="@") {
		  $cals_others[] = array($row2["dcalendar"],get_real_calendar_name($row2["dcalendar"]));
		} else {
		  $cals_users[] = array($row2["dcalendar"],ucfirst(get_real_calendar_name($row2["dcalendar"])));
	    }
	  }
	}
	
	if (!get_right_cal2($dcalendar,"modify")) $smarty->assign("disable_btn_change", 1); 
	if (!get_right_cal2($dcalendar,"delete")) $smarty->assign("disable_btn_delete", 1); 

    $dsummary = $row["dsummary"];
    $dlocation = $row["dlocation"];
    $dhomepage = $row["dhomepage"];
    $ddesc = $row["ddesc"];
    $drep_freq = $row["drep_freq"];
    $drep_interval = $row["drep_interval"];
    $drep_count = $row["drep_count"];
    $dcategories = explode(",",$row["dcategories"]);
      
    $dorganizer = $row["dorganizer"];
    $dattendee = $row["dattendee"];
    $dattendee_non = $row["dattendee_non"];
    $doptional = $row["doptional"];

    $start_year = substr($row["dstart"],0,4);
    $start_month = substr($row["dstart"],4,2);
    $start_day = substr($row["dstart"],6,2);

    if (strlen($row["dstart"]) > 8 and strlen($row["dend"]) > 8) {
      $dstart = substr($row["dstart"],9,4);
      $dend = substr($row["dend"],9,4);
    } else {
      $dentireday = "checked";
    }

    $end_year = substr($row["dend"],0,4);
    $end_month = substr($row["dend"],4,2);
    $end_day = substr($row["dend"],6,2);

    if ($row["drep_until"]!="forever") {
      $rep_year = substr($row["drep_until"],0,4);
      $rep_month = substr($row["drep_until"],4,2);
      $rep_day = substr($row["drep_until"],6,2);
      $dforever = "";
    } else {
      $dforever = "checked";
    }
        
    $dclass = $row["dclass"];
      
    if (!$row["drep_days"] and $drep_freq=="weekly") {$drep_freq = "none"; $drep_until = ""; $drep_interval = 0; $drep_count = 0;}
    if ($drep_freq=="none") {$row["drep_days"] = ""; $drep_until = ""; $drep_interval = 0; $drep_count = 0;}
        
    if ($row["drep_days"]) {
      $days = explode(",",$row["drep_days"]);
      foreach ($days as $day) {
        if ($day=="mo") { $drep_day_mo = "checked"; }
        if ($day=="tu") { $drep_day_tu = "checked"; }
        if ($day=="we") { $drep_day_we = "checked"; }
        if ($day=="th") { $drep_day_th = "checked"; }
        if ($day=="fr") { $drep_day_fr = "checked"; }
        if ($day=="sa") { $drep_day_sa = "checked"; }
        if ($day=="su") { $drep_day_su = "checked"; }
      }
    }
  } else {
    $access_denied = true;
    $close_window = true;
  }
}


if ($edit_id=="" and !$close_window) {
  $dcalendar = "";
  
  $sql = "SELECT dcalendar FROM mgw_calendar2_cals order by dcalendar";
  if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  while($row2 = $res2->FetchRow()) {
	if (get_right_cal2($row2["dcalendar"],"create")) {
      if (is_numeric($row2["dcalendar"])) {
		$cals_groups[] = array($row2["dcalendar"],get_real_calendar_name($row2["dcalendar"]));
	  } elseif ($row2["dcalendar"][0]=="#") {
		$cals_holidays[] = array($row2["dcalendar"],get_real_calendar_name($row2["dcalendar"]));
	  } elseif ($row2["dcalendar"][0]=="@") {
		$cals_others[] = array($row2["dcalendar"],get_real_calendar_name($row2["dcalendar"]));
	  } else {
		$cals_users[] = array($row2["dcalendar"],ucfirst(get_real_calendar_name($row2["dcalendar"])));
	  }
	}
  }
}
if (!$close_window and count($cals_users)==0 and count($cals_groups)==0 and count($cals_holidays)==0 and count($cals_others)==0) {
  $access_denied = true;
  $close_window = true;
}


if ($access_denied) {
  echo "<script>alert('".addslashes($hashmap["access_denied"])."')</script>";
}
if ($reload_parent and !$redirect_webmail) {
 echo "<script>window.opener.document.location.reload();</script>";
} elseif ($redirect_webmail) {
  echo "<script>window.opener.document.location='../webmail2/index.php?rightframe=sendmail.php?&".SID."';</script>";
}
if ($close_window) {
  echo "<script>window.close();</script>";
  exit;
}

// create selectboxes
if (!$start_day) {$start_day = $sdate["mday"];}
if (!$end_day) {$end_day = $sdate["mday"];}
if (!$rep_day) {$rep_day = $sdate["mday"];}
    
if (!$start_month) {$start_month = $sdate["mon"];}
if (!$end_month) {$end_month = $sdate["mon"];}
if (!$rep_month) {$rep_month = $sdate["mon"];}
   
if (!$start_year) {$start_year = $sdate["year"];}
if (!$end_year) {$end_year = $sdate["year"];}
if (!$rep_year) {$rep_year = $sdate["year"];}


$smarty->assign("cals_users",$cals_users);
$smarty->assign("cals_groups",$cals_groups);
$smarty->assign("cals_holidays",$cals_holidays);
$smarty->assign("cals_others",$cals_others);
	
$smarty->assign("dcalendar",$dcalendar);


// days
$sdays = new mSelectBox("start_day");
$smarty->assign("serial_start_day", $sdays->getSB_Day($start_day, false));
$smarty->assign("start_day",$start_day);

$sdays = new mSelectBox("end_day");
$smarty->assign("serial_end_day", $sdays->getSB_Day($end_day, false));
$smarty->assign("end_day",$end_day);

$sdays = new mSelectBox("rep_day");
$smarty->assign("serial_rep_day", $sdays->getSB_Day($rep_day, false));
$smarty->assign("rep_day",$rep_day);

// months
$smonths = new mSelectBox("start_month");
$smarty->assign("serial_start_month", $smonths->getSB_Month($start_month,false));
$smarty->assign("start_month",$start_month);

$smonths = new mSelectBox("end_month");
$smarty->assign("serial_end_month", $smonths->getSB_Month($end_month,false));
$smarty->assign("end_month",$end_month);

$smonths = new mSelectBox("rep_month");
$smarty->assign("serial_rep_month", $smonths->getSB_Month($rep_month,false));
$smarty->assign("rep_month",$rep_month);

// years
$syears = new mSelectBox("start_year");
$smarty->assign("serial_start_year", $syears->getSB_Year(2000,2010,$start_year),false);
$smarty->assign("start_year",$start_year);

$syears = new mSelectBox("end_year");
$smarty->assign("serial_end_year", $syears->getSB_Year(2000,2010,$end_year),false);
$smarty->assign("end_year",$end_year);

$syears = new mSelectBox("rep_year");
$smarty->assign("serial_rep_year", $syears->getSB_Year(2000,2010,$rep_year),false);
$smarty->assign("rep_year",$rep_year);

$app_start_time = 0;
// (substr($day_start,0,2)-1)*3600+substr($day_start,2,2)*60
$app_end_time = 24*3600;
// (substr($day_end,0,2)-1)*3600+substr($day_end,2,2)*60

$timemask = "H:i";
$timemask2 = "Hi";
$interval_sec = $gridLength*60;

if ($dstart=="") { 
  $dstart = twodigit($sdate["hours"]).twodigit($sdate["minutes"]-($sdate["minutes"] % $gridLength));
  $dend = $sdate["hours"]*3600 + ($sdate["minutes"] - ($sdate["minutes"] % $gridLength))*60 + 1800;
  $dend = twodigit(floor(($dend) / 3600)).twodigit((($dend) % 3600)/60);
}

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

for( $t=$app_start_time; $t < $app_end_time; $t+=$interval_sec) {
  $timestamp_h = twodigit(floor($t / 3600));
  $timestamp_l = twodigit(($t % 3600)/60);

  $timestamp2 = $timestamp_h.$timestamp_l;
  $timestamp = $timestamp2;

  ereg('([0-9]{2})([0-9]{2})', $timestamp, $regs_tmp);
  $timestamp = mktime($regs_tmp[1],$regs_tmp[2],0,$this_month,$this_day,$this_year);
  $timestamp = date ($hashmap["timeFormat"], $timestamp);

  $dstart2 = array(
	"timestamp" 	=> $timestamp2,
	"time_label"  	=> $timestamp,
	"sel" 		=> ($dstart==$timestamp2 ? " selected" : "")
  );

  $timestamp_h = twodigit(floor(($t+$interval_sec) / 3600));
  $timestamp_l = twodigit((($t+$interval_sec) % 3600)/60);

  $timestamp2 = $timestamp_h.$timestamp_l;
  $timestamp = $timestamp2;

  ereg('([0-9]{2})([0-9]{2})', $timestamp, $regs_tmp);
  $timestamp = mktime($regs_tmp[1],$regs_tmp[2],0,$this_month,$this_day,$this_year);
  $timestamp = date ($hashmap["timeFormat"], $timestamp);

  $dend2 = array(
	"timestamp" => $timestamp2,
	"time_label" => $timestamp,
	"sel"   => ($dend==$timestamp2 ? " selected" : "")
  );
  $smarty->append("dstart", $dstart2);
  $smarty->append("dend", $dend2);
}

$categories = array("Birthday","Business","Calls","Clients","Competition","Customer","Favorites","Follow up","Gifts","Goals","Holidays","Ideas","Issues","Miscellaneous","Personal","Projects","Public Holiday","Status","Suppliers","Time & Expenses","Travel","Vacation");

$dcategories2 = array();
foreach ($categories as $category) {
  $dcategories2[] = array($category,$hashmap[str_replace(array(" ","&"),"_",strtolower($category))],(in_array($category,$dcategories)?"selected":""));
}

$smarty->assign("dcategories_arr",$dcategories2);
$smarty->assign("dforever",$dforever);
$smarty->assign("dcategories",$dcategories);
$smarty->assign("has_dcategories",(isset($dcategories[0]) and $dcategories[0]!=""));
$smarty->assign("dsummary",$dsummary);

$smarty->assign("dorganizer",$dorganizer);
$smarty->assign("dattendee",$dattendee);
$smarty->assign("dattendee_non",$dattendee_non);
$smarty->assign("doptional",$doptional);

$smarty->assign("dlocation",$dlocation);
$smarty->assign("dhomepage",$dhomepage);
$smarty->assign("ddesc",$ddesc);

$smarty->assign("drep_freq",($drep_freq?$drep_freq:"none"));
$smarty->assign("drep_interval",($drep_interval?$drep_interval:1));
$smarty->assign("drep_count",($drep_count?$drep_count:0));

$smarty->assign("dclass",$dclass);
$smarty->assign("dentireday",($dentireday?" checked":""));

$smarty->assign("drep_day_mo",($drep_day_mo?" checked":""));
$smarty->assign("drep_day_tu",($drep_day_tu?" checked":""));
$smarty->assign("drep_day_we",($drep_day_we?" checked":""));
$smarty->assign("drep_day_th",($drep_day_th?" checked":""));
$smarty->assign("drep_day_fr",($drep_day_fr?" checked":""));
$smarty->assign("drep_day_sa",($drep_day_sa?" checked":""));
$smarty->assign("drep_day_su",($drep_day_su?" checked":""));

$smarty->assign("custom_font",$_SESSION["MGW"]->settings["cal2_compose_font"]);
$smarty->assign("custom_font_size",$_SESSION["MGW"]->settings["cal2_compose_font_size"]);

$smarty->assign("calendar_lang",$hashmap["calendar_lang"]);
$smarty->assign("wm2_installed",isModuleInstalled("webmail2"));

$smarty->assign("id",$edit_id);

$hashmap["dow_lang"] = explode(",",$hashmap["dow_lang"]);
$smarty->assign("hashmap",$hashmap);


$contacts = array();
get_calendar_users($hashmap["compose_users"]);
get_calendar_groups($hashmap["compose_groups"]);
get_calendar_contacts($_SESSION["MGW"]->userid,$hashmap["compose_contacts"]);
get_calendar_companies($_SESSION["MGW"]->userid,$hashmap["compose_companies"]);
get_calendar_contact_groups($hashmap["compose_contact_groups"]);

$contacts_str = '';
foreach ($contacts as $contact) {
  $contacts_str .= '<OPTION VALUE="'.strtolower($contact[1]).'">'.$contact[0];
}

$smarty->assign("contacts", $contacts_str);
	  

$smarty->display("calendar2_app_edit.tpl");

?>
