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

// calendar2_func
// Moregroupware.org

define('CAL2_INC_DIR', ROOTPATH."/modules/calendar2/inc/");
define('IMGPATH',$appconf["imgpath"]);

$calendar2_footer = "<center><font class=\"V9\"><br>Powered by &nbsp;<a class=\"psf\" target=\"_blank\" href=\"http://moregroupware.sourceforge.net/\" style=\"font-size=12px\">more.groupware</a>&nbsp; and <a target=\"_blank\" class=\"psf\" href=\"http://phpicalendar.sourceforge.net/nuke/\">PHP iCalendar 0.9.1</a></font></center>";

if (get_magic_quotes_gpc() == 1){
  if (is_array($_POST) and count($_POST)>0)
 while (list ($key, $val) = each ($_POST)){
    $_POST[$key] = stripslashes_array($val);
 }
  if (is_array($_GET) and count($_GET)>0)
 while (list ($key, $val) = each ($_GET)){
    $_GET[$key] = stripslashes_array($val);
 }
  if (is_array($_COOKIE) and count($_COOKIE)>0)
  while (list ($key, $val) = each ($_COOKIE)){
    $_COOKIE[$key] = stripslashes_array($val);
 }
}


function get_calendar_display($calendar) {
  $calendar2 = "";
  if (is_numeric($calendar)) $calendar2 .= "@";
  $calendar2 .= ucfirst(get_real_calendar_name($calendar));
  return $calendar2;
}


function make_homepage($my_key,$linebreak) {
  global $all_cals;
  
  $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");
  $hp = "";
  if ($all_cals[$my_key]["homepage"]!="") {
    $hp = '<a href="norefer.php?url='.$all_cals[$my_key]["homepage"].'" onclick="event.cancelBubble=true;" target="_blank"><img src="templates/default/media/link.gif" align="absmiddle" alt="" border="0"></a>';
  }
  if (isset($all_cals[$my_key]["dorganizer"]) and (($all_cals[$my_key]["dorganizer"]!="" and strpos($all_cals[$my_key]["dorganizer"],",")) or $all_cals[$my_key]["dattendee"]!="" or $all_cals[$my_key]["dattendee_non"]!="" or $all_cals[$my_key]["doptional"]!="")) {
    $hp .= '&nbsp;<img border="0" src="templates/default/media/team.gif" alt="" align="absmiddle">&nbsp;&nbsp;';
  }
  
  if ($all_cals[$my_key]["categories"]!="") {
    $cats = explode(",",$all_cals[$my_key]["categories"]);
	if ($hp!="" and $linebreak) $hp .= "<br>";
	foreach ($cats as $cat) {
	  if (in_array(str_replace(array(" ","&"),"_",strtolower($cat)),$categories)) {
  	    $hp .= '<img align="absmiddle" border="0" src="templates/default/media/'.str_replace(array(" ","&"),"_",strtolower($cat)).'.gif" alt="'.addslashes($cat).'">&nbsp;';
	  }
	}
  }

  return $hp;
}


function make_dadd($my_key) {
  global $all_cals;

  $dadd = ",'".$all_cals[$my_key]["dorganizer"]."','".$all_cals[$my_key]["dattendee"]."','".$all_cals[$my_key]["dattendee_non"]."','".$all_cals[$my_key]["doptional"]."','".$all_cals[$my_key]["daccepted"]."','".$all_cals[$my_key]["ddeclined"]."','".$all_cals[$my_key]["dtentative"]."'";
  return $dadd;
}


function has_access($cal2_entry,$type="write") {
  $return = false;
  if ($cal2_entry["c_duser_id"]==$_SESSION["MGW"]->userid) $return = true;
  //  or $cal2_entry["duser_id"]==$_SESSION["MGW"]->userid

  if (isset($cal2_entry["dorganizer"]) and $cal2_entry["dorganizer"]!="") $cal2_entry["dorganizer"] = trim(str_replace(" ","",strtolower($cal2_entry["dorganizer"])),",");
  if (isset($cal2_entry["dattendee"]) and $cal2_entry["dattendee"]!="") $cal2_entry["dattendee"] = trim(str_replace(" ","",strtolower($cal2_entry["dattendee"])),",");
  if (isset($cal2_entry["dattendee_non"]) and $cal2_entry["dattendee_non"]!="") $cal2_entry["dattendee_non"] = trim(str_replace(" ","",strtolower($cal2_entry["dattendee_non"])),",");
  if (isset($cal2_entry["doptional"]) and $cal2_entry["doptional"]!="") $cal2_entry["doptional"] = trim(str_replace(" ","",strtolower($cal2_entry["doptional"])),",");
  
  if (!$return and $cal2_entry["dclass"]=="confidential") {
	if (isset($cal2_entry["dorganizer"]) and $cal2_entry["dorganizer"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dorganizer"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dorganizer"])))) $return = true;
	if ($type=="read") {
  	  if (isset($cal2_entry["dattendee"]) and $cal2_entry["dattendee"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dattendee"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dattendee"])))) $return = true;
        if (isset($cal2_entry["doptional"]) and $cal2_entry["doptional"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["doptional"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["doptional"])))) $return = true;
    }
  	  if (isset($cal2_entry["dattendee_non"]) and $cal2_entry["dattendee_non"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dattendee_non"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dattendee_non"])))) $return = true;

	if (!isset($cal2_entry["viewconfidential"])) $cal2_entry["viewconfidential"] = get_right_cal2($cal2_entry["dcalendar"],"viewconfidential");
	if (!$return and $cal2_entry["viewconfidential"]) $return = true;
  } elseif (!$return and $cal2_entry["dclass"]=="private") {
	if (isset($cal2_entry["dorganizer"]) and $cal2_entry["dorganizer"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dorganizer"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dorganizer"])))) $return = true;
	if ($type=="read") {
  	  if (isset($cal2_entry["dattendee"]) and $cal2_entry["dattendee"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dattendee"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dattendee"])))) $return = true;
        if (isset($cal2_entry["doptional"]) and $cal2_entry["doptional"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["doptional"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["doptional"])))) $return = true;
    }
  	  if (isset($cal2_entry["dattendee_non"]) and $cal2_entry["dattendee_non"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dattendee_non"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dattendee_non"])))) $return = true;

	if (!isset($cal2_entry["viewprivate"])) $cal2_entry["viewprivate"] = get_right_cal2($cal2_entry["dcalendar"],"viewprivate");
	if (!$return and $cal2_entry["viewprivate"]) $return = true;
  } elseif (!$return and $cal2_entry["dclass"]=="public" and $type!="read") {
	if (isset($cal2_entry["dorganizer"]) and $cal2_entry["dorganizer"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dorganizer"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dorganizer"])))) $return = true;
    if (isset($cal2_entry["dattendee_non"]) and $cal2_entry["dattendee_non"]!="" and (is_numeric(array_search($_SESSION["MGW"]->username,explode(",",$cal2_entry["dattendee_non"]))) or multi_search($_SESSION["MGW"]->groups_names,explode(",",$cal2_entry["dattendee_non"])))) $return = true;

	if (!isset($cal2_entry["viewprivate"])) $cal2_entry["viewprivate"] = get_right_cal2($cal2_entry["dcalendar"],"viewprivate");
	if (!$return and $cal2_entry["viewprivate"]) $return = true;
  } else $return = true;
  
  return $return;
}

function multi_search($map,$row) {
  foreach ($map as $map2) {
    foreach($row as $cell) {
      if (strtolower($cell) == $map2) return true;
    }
  } 
  return false;
}

function get_array_from_string($my_str) {
  if ($my_str!="") {
	$my_arr = explode(",",$my_str);
	foreach ($my_arr as $key=>$key2) $my_arr[$key] = addslashes(htmlspecialchars(strip_tags($my_arr[$key])));
  } else $my_arr = array();
  return $my_arr;
}
	  

function build_rep_showmenu($my_obj,$my_key) {
  global $hashmap,$all_cals;
  
  $drep = "";
  $my_until = "";
  $my_days = "";

  if (isset($my_obj["BYDAY"]) and is_array($my_obj["BYDAY"]) and count($my_obj["BYDAY"])>0) {

    foreach ($my_obj["BYDAY"] as $my_item) {
	  $my_item=strtolower($my_item);
	  if ($my_item=="mo") $my_days .= ",".$hashmap["dow_lang"][0];
	  if ($my_item=="tu") $my_days .= ",".$hashmap["dow_lang"][1];
	  if ($my_item=="we") $my_days .= ",".$hashmap["dow_lang"][2];
	  if ($my_item=="th") $my_days .= ",".$hashmap["dow_lang"][3];
	  if ($my_item=="fr") $my_days .= ",".$hashmap["dow_lang"][4];
	  if ($my_item=="sa") $my_days .= ",".$hashmap["dow_lang"][5];
	  if ($my_item=="su") $my_days .= ",".$hashmap["dow_lang"][6];
	}
	if ($my_days!="") $my_days = substr($my_days,1);
  }
  
  if ($all_cals[$my_key]["row"]["drep_until"]!="" and isset($my_obj["UNTIL"])) {
    $my_obj["UNTIL"] = strtotime2(substr($all_cals[$my_key]["row"]["drep_until"],0,8));
    $my_until = localizeDate($hashmap["dateFormat_week_list"]." %Y", $my_obj["UNTIL"]);
  }
  return ',\''.(isset($hashmap[$my_obj["FREQ"]])?$hashmap[$my_obj["FREQ"]]:$my_obj["FREQ"]).'\',\''.$my_until.'\',\''.$my_days.'\',\''.(isset($my_obj["COUNT"])?$my_obj["COUNT"]:"").'\',\''.(isset($my_obj["INTERVAL"])?$my_obj["INTERVAL"]:"").'\'';
}

function store_calendar_cals($icals) {
  $_POST["option"] = "";
  require_once("../settings/inc/settings_func.inc.php");
  store_flag ("cal2_icals","calendar2","txt");
  updateSettingsInDB("cal2_icals", $icals);
}

function store_calendar_view($view) {
  $_POST["option"] = "";
  require_once("../settings/inc/settings_func.inc.php");
  store_flag ("cal2_default_view","calendar2","str");
  updateSettingsInDB("cal2_default_view", $view);
}

function store_calendar_date($getdate) {
  $_SESSION["MGW"]->settings["cal2_default_day"] = $getdate;
}

function make_event_str_participants($my_str,$event_str2) {
  global $conn;
  
  $event_str = "";
  $my_arr = explode(",",$my_str);
  foreach ($my_arr as $my_item) {
    $my_item = trim($my_item);
    if ($my_item!="" and $my_item[0]!="@" and !strpos($my_item,"@") > 0) {
      $sql = "select firstname,lastname,username,email from mgw_users where username=".$conn->Quote($my_item);
      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 .= $event_str2.";CN=\"".$row2["firstname"]." ".$row2["lastname"]."\"".$row2["email"]."\n";
	  }
	} elseif ($my_item[0]=="@") {
      $event_str .= $event_str2.";CN=\"".substr($my_item,1)."\":MAILTO:".$my_item."\n";
	} else {
      $event_str .= $event_str2.";CN=\"".$my_item."\":MAILTO:".$my_item."\n";
	}
  }
  return $event_str;
}


function strip_empty_items($my_arr) {
  $new_arr = array();
  if (is_array($my_arr) and count($my_arr)>0) {
    foreach ($my_arr as $key=>$key2) {
      if ($key2!="") $new_arr[] = $key2;
    }
  }
  return $new_arr;
}

function get_calendar_users ($message) {
  global $conn,$contacts;
  
  $contacts[count($contacts)] = array("--------------- ".$message." ---------------","");

  $sql = "SELECT a.username,a.email,a.lastname,a.firstname FROM mgw_users a where a.email<>'' order by lastname";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  while($row = $res->FetchRow()) {
	if (isset($row["firstname"]) and $row["firstname"]!="") {$row["firstname"] .= " ";} else {$row["firstname"] = "";}
	if (isset($_SESSION["MGW"]->settings["wm2_reverse_contacts"]) and $_SESSION["MGW"]->settings["wm2_reverse_contacts"]) {
	  $contacts[count($contacts)][0] = htmlspecialchars($row["lastname"].", ".$row["firstname"]." <".$row["email"].">");
	} else {
	$contacts[count($contacts)][0] = htmlspecialchars($row["firstname"].$row["lastname"]." <".$row["email"].">");
	}
	$contacts[count($contacts)-1][1] = htmlspecialchars($row["username"]);
  } 	
}

function get_calendar_groups ($message) {
  global $conn,$contacts;

  $contacts[count($contacts)] = array("--------------- ".$message." ---------------","");

  $sql = "SELECT name,description FROM mgw_groups order by name";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  while($row = $res->FetchRow()) {
	if ($row["description"]!="") {$description = " (".$row["description"].")";} else {$description="";}
	$contacts[count($contacts)][0] = htmlspecialchars($row["name"].$description);
	$contacts[count($contacts)-1][1] = htmlspecialchars("@".$row["name"]);
  }	
}

function get_calendar_contacts ($user_id,$message) {
  global $conn,$contacts;

  if (isModuleInstalled("contact")) {
  $contacts[count($contacts)] = array("--------------- ".$message." ---------------","");

  $sql = "SELECT a.email,a.lastname,a.firstname FROM mgw_contacts a where a.email<>'' and (a.ispublic=1 or a.owner=".(int)$user_id.") order by lastname";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  while($row = $res->FetchRow()) {
	if (isset($_SESSION["MGW"]->settings["wm2_reverse_contacts"]) and $_SESSION["MGW"]->settings["wm2_reverse_contacts"]) {
	  if (isset($row["firstname"]) and $row["firstname"]!="") {$row["firstname"] = ", ".$row["firstname"];} else {$row["firstname"] = "";}
	  $contacts[count($contacts)][0] = htmlspecialchars($row["lastname"].$row["firstname"]." <".$row["email"].">");
	} else {
	if (isset($row["firstname"]) and $row["firstname"]!="") {$row["firstname"] .= " ";} else {$row["firstname"] = "";}
	$contacts[count($contacts)][0] = htmlspecialchars($row["firstname"].$row["lastname"]." <".$row["email"].">");
	}
	$contacts[count($contacts)-1][1] = htmlspecialchars($row["email"]);
  }	
}
}

function get_calendar_companies ($user_id,$message) {
  global $conn,$contacts;

  if (isModuleInstalled("contact")) {
  $contacts[count($contacts)] = array("--------------- ".$message." ---------------","");

  $sql = "SELECT name1,email FROM mgw_companies where email<>'' and (ispublic=1 or owner=".(int)$user_id.") order by name1";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  while($row = $res->FetchRow()) {
	$contacts[count($contacts)][0] = htmlspecialchars($row["name1"]." <".$row["email"].">");
	$contacts[count($contacts)-1][1] = htmlspecialchars($row["email"]);
  }	
}
}

function get_calendar_contact_groups ($message) {
  global $conn,$contacts;

  if (isModuleInstalled("contact")) {
  $contacts[count($contacts)] = array("--------------- ".$message." ---------------","");

  $sql = "SELECT name_key,id FROM mgw_contacts_groups order by name_key";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

  while($row = $res->FetchRow()) {
	$contacts[count($contacts)][0] = htmlspecialchars($row["name_key"]);
	$contacts[count($contacts)-1][1] = htmlspecialchars("@".$row["name_key"]);
  }	
}
}


function modify_html($ddesc) {
  $ddesc = preg_replace(array(
	"'<script[^>]*?>.*?</script[^>]*?>'si",
	"'<applet[^>]*?>.*?</applet[^>]*?>'si",
	"'<object[^>]*?>.*?</object[^>]*?>'si",
	"'<iframe[^>]*?>.*?</iframe[^>]*?>'si",
	"'<frameset[^>]*?>.*?</frameset[^>]*?>'si",
	"'<style[^>]*?>.*?</style[^>]*?>'si",
	"'<marquee[^>]*?>.*?</marquee[^>]*?>'si",
	"'<script[^>]*?>'si",
	"'<meta[^>]*?>'si",
	"'<base[^>]*?>'si",
	"'<applet[^>]*?>'si",
	"'<object[^>]*?>'si",
	"'<link[^>]*?>'si",
	"'<iframe[^>]*?>'si",
	"'<frame[^>]*?>'si",
	"'<frameset[^>]*?>'si",
	"'<input[^>]*?>'si",
	"'<form[^>]*?>'si",
	"'<img[^>]*?>'si",
	"'<embed[^>]*?>'si",
	"'background-image:url'si",
	"'<\w+ .*?(javascript:|onabort|onbeforeunload|onblur|onchange|onclick|ondblclick|ondragdrop|onerror|onfilterchange|onfocus|onhelp|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onmove|onreadystatechange|onreset|onresize|onscroll|onselect|onselectstart|onsubmit|onunload).*?>'si",
  ), '', $ddesc);

  $pattern = '=(.*)<a.*href\=[ ]*[\'"]([^#"]*)[\'"][^>]*>(.*)</a>(.*)=msiU';
  $ddesc = preg_replace_callback($pattern, "modify_my_callback", $ddesc);

  return $ddesc;
}

function modify_my_callback($s) {
  if (strpos("@".$s[2],"mailto:")==1) {
    $repl = $s[1].'<a target="rightframe" href="'.ROOTURL.'/modules/webmail2/sendmail.php?to='.str_replace("mailto:","",addslashes(strip_tags($s[2]))).'">'.$s[3].'</a>'.$s[4];
  } else {
    $repl = $s[1].'<a target="_blank" href="norefer.php?url='.addslashes(strip_tags($s[2])).'">'.$s[3].'</a>'.$s[4];
  }
  return $repl;
}

// localizeDate() - similar to strftime but uses our preset arrays of localized
// months and week days and only supports %A, %a, %B, %b, %e, and %Y
// more can be added as needed but trying to keep it small while we can
function localizeDate($format, $timestamp) {
	global $daysofweek_lang, $daysofweekshort_lang, $daysofweekreallyshort_lang, $monthsofyear_lang, $monthsofyear_lang, $monthsofyearshort_lang;
	$year = date("Y", $timestamp);
	$month = date("n", $timestamp)-1;
	$day = date("j", $timestamp);
	$dayofweek = date("w", $timestamp);
	
	$date = str_replace('%Y', $year, $format);
	$date = str_replace('%e', $day, $date);
	$date = str_replace('%B', $monthsofyear_lang[$month], $date);
	$date = str_replace('%b', (isset($monthsofyearshort_lang[$month])?$monthsofyearshort_lang[$month]:""), $date);
	$date = str_replace('%A', $daysofweek_lang[$dayofweek], $date);
	$date = str_replace('%a', $daysofweekshort_lang[$dayofweek], $date);
	
	return $date;	
}

function get_real_calendar_name($calendar) {
  if ($calendar=="") return "";
  if (is_numeric($calendar)) return get_group_name($calendar);
  if ($calendar[0]=="#" or $calendar[0]=="@") return substr($calendar,1);
  return $calendar;
}

function get_calendar_id($calendar) {
  global $conn;

  $sql = "SELECT id FROM mgw_calendar2_cals where dcalendar=".$conn->Quote($calendar);
  if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  $row = $res->FetchRow();

  if (isset($row["id"]) and is_numeric($row["id"])) return $row["id"];
    else return 0;
}

function get_type_calendar($calendar) {
  global $hashmap; 
  
  if ($calendar=="") return $hashmap["none"];

  if (is_numeric($calendar)) return $hashmap["groups"];
  if ($calendar[0]=="#") return $hashmap["holidays"];
  if ($calendar[0]=="@") return $hashmap["others"];
  return $hashmap["users"];
}

function get_right_cal2($calendar, $right) {
  global $conn;

  if ($calendar=="") return false;
  if (is_numeric($calendar)) return queryRights2_bool("root_modules_calendar2_groupcalendars_".get_calendar_id($calendar)."_".$right);

  if ($calendar[0]=="#") return queryRights2_bool("root_modules_calendar2_holidaycalendars_".get_calendar_id($calendar)."_".$right);
  if ($calendar[0]=="@") return queryRights2_bool("root_modules_calendar2_publiccalendars_".get_calendar_id($calendar)."_".$right);

  return queryRights2_bool("root_modules_calendar2_personalcalendars_".get_calendar_id($calendar)."_".$right);
}

function twodigit($str) {
  return (strlen($str)==1?"0".$str:$str);
}

// dateOfWeek() takes a date in Ymd and a day of week in 3 letters or more
// and returns the date of that day. (ie: "sun" or "sunday" would be acceptable values of $day but not "su")
function dateOfWeek($Ymd, $day) {
	global $week_start_day;
	if (!isset($week_start_day)) $week_start_day = 'Sunday';
	$timestamp = strtotime2($Ymd);
	$num = date('w', strtotime2($week_start_day));
	$start_day_time = strtotime2((date('w',$timestamp)==$num ? "$week_start_day" : "last $week_start_day"), $timestamp);
	$ret_unixtime = strtotime2($day,$start_day_time);
	$ret_unixtime = strtotime2('+12 hours', $ret_unixtime);
	$ret = date('Ymd',$ret_unixtime);
	return $ret;
}

// takes iCalendar 2 day format and makes it into 3 characters
// if $txt is true, it returns the 3 letters, otherwise it returns the
// integer of that day; 0=Sun, 1=Mon, etc.
function two2threeCharDays($day, $txt=true) {
	switch($day) {
		case 'SU': return ($txt ? 'sun' : '0');
		case 'MO': return ($txt ? 'mon' : '1');
		case 'TU': return ($txt ? 'tue' : '2');
		case 'WE': return ($txt ? 'wed' : '3');
		case 'TH': return ($txt ? 'thu' : '4');
		case 'FR': return ($txt ? 'fri' : '5');
		case 'SA': return ($txt ? 'sat' : '6');
	}
}

// function to compare to dates in Ymd and return the number of weeks 
// that differ between them. requires dateOfWeek()
function weekCompare($now, $then) {
	global $week_start_day;
	$sun_now = dateOfWeek($now, $week_start_day);
	$sun_then = dateOfWeek($then, $week_start_day);
	$seconds_now = strtotime2($sun_now);
	$seconds_then =  strtotime2($sun_then);
	$diff_seconds = $seconds_now - $seconds_then;
	$diff_minutes = $diff_seconds/60;
	$diff_hours = $diff_minutes/60;
	$diff_days = round($diff_hours/24);
	$diff_weeks = $diff_days/7;
	
	return $diff_weeks;
}

// function to compare to dates in Ymd and return the number of days 
// that differ between them.
function dayCompare($now, $then) {
	$seconds_now = strtotime2($now);
	$seconds_then =  strtotime2($then);
	$diff_seconds = $seconds_now - $seconds_then;
	$diff_minutes = $diff_seconds/60;
	$diff_hours = $diff_minutes/60;
	$diff_days = round($diff_hours/24);
	
	return $diff_days;
}

// function to compare to dates in Ymd and return the number of months 
// that differ between them.
function monthCompare($now, $then) {
	ereg ("([0-9]{4})([0-9]{2})([0-9]{2})", $now, $date_now);
	ereg ("([0-9]{4})([0-9]{2})([0-9]{2})", $then, $date_then);
	$diff_years = $date_now[1] - $date_then[1];
	$diff_months = $date_now[2] - $date_then[2];
	if ($date_now[2] < $date_then[2]) {
		$diff_years -= 1;
		$diff_months = ($diff_months + 12) % 12;
	}
	$diff_months = ($diff_years * 12) + $diff_months;

	return $diff_months;
}

function yearCompare($now, $then) {
	ereg ("([0-9]{4})([0-9]{2})([0-9]{2})", $now, $date_now);
	ereg ("([0-9]{4})([0-9]{2})([0-9]{2})", $then, $date_then);
	$diff_years = $date_now[1] - $date_then[1];
	return $diff_years;
}

// calcOffset takes an offset (ie, -0500) and returns it in the number of seconds
function calcOffset($offset_str) {
	$sign = substr($offset_str, 0, 1);
	$hours = substr($offset_str, 1, 2);
	$mins = substr($offset_str, 3, 2);
	$secs = ((int)$hours * 3600) + ((int)$mins * 60);
	if ($sign == '-') $secs = 0 - $secs;
	return $secs;
}

// calcTime calculates the unixtime of a new offset by comparing it to the current offset
// $have is the current offset (ie, '-0500')
// $want is the wanted offset (ie, '-0700')
// $time is the unixtime relative to $have
function calcTime($have, $want, $time) {
	if ($have == 'none' || $want == 'none') return $time;
	$have_secs = calcOffset($have);
	$want_secs = calcOffset($want);
	$diff = $want_secs - $have_secs;
	$time += $diff;
	return $time;
}

function chooseOffset($time) {
	global $tz_array;

	$timezone = $_SESSION["MGW"]->settings["cal2_timezone"];
	switch ($timezone) {
		case '':
			$offset = 'none';
			break;
		case 'Same as Server':
			$offset = date('O', $time);
			break;
		default:
			if (is_array($tz_array) && array_key_exists($timezone, $tz_array)) {
				$dlst = date('I', $time);
				$offset = $tz_array[$timezone][$dlst];
			} else {
				$offset = '+0000';
			}
	}
	return $offset;
}

// function to determine maximum necessary columns per day
// actually an algorithm to get the smallest multiple for two numbers
function kgv($a, $b) {
	$x = $a;
	$y = $b;
	while ($x != $y) {
		if ($x < $y) $x += $a;
		else $y += $b;
	}
	return $x;
}

// drei 20020921: function for checking and counting overlapping events
// drei 20020212: added parameter uid to function call
function checkOverlap($ol_start_date, $ol_start_time, $ol_end_time, $ol_uid) {
	global $master_array, $overlap_array,$day_start,$day_end,$gridLength;

        $day_start2 = date("Hi",strtotime2($day_start)+$gridLength*60);
        $day_end2 = date("Hi",strtotime2($day_end)-$gridLength*60);

        if ($ol_start_time <= $day_start2) {
		  $drawTimes = drawEventTimes("0000", $day_start2);
        } elseif ($ol_end_time >= $day_end2) {
		  $drawTimes = drawEventTimes($day_end2, "2400");
        } else {
          $drawTimes = drawEventTimes($ol_start_time, $ol_end_time);
        }        
		$newMasterTime = $drawTimes["draw_start"];

		$realdrawTimes = drawEventTimes($ol_start_time, $ol_end_time);
		$realMasterTime = $realdrawTimes["draw_start"];

		// if (isset($master_array[($ol_start_date)][($newMasterTime)])) $newMasterEventKey = sizeof($master_array[($ol_start_date)][($newMasterTime)]);
		// else $newMasterEventKey = 0;
		
		$maxOverlaps = 0;
		$newEventAdded = FALSE;

		if (isset($overlap_array[$ol_start_date])) {
			foreach ($overlap_array[($ol_start_date)] as $loopBlockKey => $loopBlock) {
				// check for overlap with existing overlap block
				if (($loopBlock["blockStart"] < $drawTimes["draw_end"]) and ($loopBlock["blockEnd"] > $drawTimes["draw_start"])) {
					$newOverlapBlock = FALSE;
					// if necessary adjust start and end times of overlap block
					if ($loopBlock["blockStart"] > $drawTimes["draw_start"]) $overlap_array[($ol_start_date)][($loopBlockKey)]["blockStart"] = $drawTimes["draw_start"];
					if ($loopBlock["blockEnd"] < $drawTimes["draw_end"]) $overlap_array[($ol_start_date)][($loopBlockKey)]["blockEnd"] = $drawTimes["draw_end"];
					// add the new event to the array of events
					// $overlap_array[($ol_start_date)][($loopBlockKey)]["events"][] = array ("time" => $newMasterTime, "key" => $newMasterEventKey);
					$overlap_array[($ol_start_date)][($loopBlockKey)]["events"][] = array ("time" => $newMasterTime,"time2" => $realMasterTime, "key" => $ol_uid);
					// check if the adjusted overlap block must be merged with an existing overlap block
					reset($overlap_array[($ol_start_date)]);
					do {
						$compBlockKey = key(current($overlap_array[($ol_start_date)]));
						// only compare with other blocks
						if ($compBlockKey != $loopBlockKey) {
							// check if blocks overlap
							if (isset($overlap_array[$ol_start_date][$compBlockKey]["blockStart"]) and ($overlap_array[$ol_start_date][$compBlockKey]["blockStart"] < $overlap_array[$ol_start_date][$loopBlockKey]["blockEnd"]) and ($overlap_array[$ol_start_date][$compBlockKey]["blockEnd"] > $overlap_array[$ol_start_date][$loopBlockKey]["blockStart"])) {
								// define start and end of merged overlap block
								if ($loopBlock["blockStart"] > $overlap_array[($ol_start_date)][($compBlockKey)]["blockStart"]) $overlap_array[($ol_start_date)][($loopBlockKey)]["blockStart"] = $overlap_array[($ol_start_date)][($compBlockKey)]["blockStart"];
								if ($loopBlock["blockEnd"] < $overlap_array[($ol_start_date)][($compBlockKey)]["blockEnd"]) $overlap_array[($ol_start_date)][($loopBlockKey)]["blockEnd"] = $overlap_array[($ol_start_date)][($compBlockKey)]["blockEnd"];
								$overlap_array[($ol_start_date)][($loopBlockKey)]["events"] = array_merge($overlap_array[($ol_start_date)][($loopBlockKey)]["events"],$overlap_array[($ol_start_date)][($compBlockKey)]["events"]);
								$overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"] = array_merge($overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"],$overlap_array[($ol_start_date)][($compBlockKey)]["overlapRanges"]);
								unset($overlap_array[($ol_start_date)][($compBlockKey)]);
								reset($overlap_array[($ol_start_date)]);
							}
						} 
					} while (next($overlap_array[($ol_start_date)]));
					// insert new event to appropriate overlap range

					$newOverlapRange = TRUE;
					foreach ($overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"] as $keyOverlap => $overlapRange) {
						if (($overlapRange["start"] < $drawTimes["draw_end"]) and ($overlapRange["end"] > $drawTimes["draw_start"])) {
							$overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"][($keyOverlap)]["count"]++;
							if ($overlapRange["start"] < $drawTimes["draw_start"]) $overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"][($keyOverlap)]["start"] = $drawTimes["draw_start"];
							if ($overlapRange["end"] > $drawTimes["draw_end"]) $overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"][($keyOverlap)]["end"] = $drawTimes["draw_end"];
							$newOverlapRange = FALSE;
		//					break;
						}
					}
					if ($newOverlapRange) {
						foreach ($loopBlock["events"] as $blockEvents) {
						  if (isset($master_array[$ol_start_date][$blockEvents["time"]][$blockEvents["key"]]["event_start"])) {
							$eventDrawTimes = drawEventTimes($master_array[($ol_start_date)][($blockEvents["time"])][($blockEvents["key"])]["event_start"], $master_array[($ol_start_date)][($blockEvents["time"])][($blockEvents["key"])]["event_end"]);
							if ((isset($eventDrawTimes["draw_start"]) && isset($eventDrawTimes["draw_end"]) && isset($drawTimes["draw_end"]) && isset($drawTimes["draw_start"])) && ($eventDrawTimes["draw_start"] < $drawTimes["draw_end"]) and ($eventDrawTimes["draw_end"] > $drawTimes["draw_start"])) {
								// define start time of overlap range and overlap block
								if ($eventDrawTimes["draw_start"] < $drawTimes["draw_start"]) $overlap_start = $drawTimes["draw_start"];
								else $overlap_start = $eventDrawTimes["draw_start"];
								// define end time of overlap range and overlap block
								if ($eventDrawTimes["draw_end"] > $drawTimes["draw_end"]) $overlap_end = $drawTimes["draw_end"];
								else $overlap_end = $eventDrawTimes["draw_end"];
								
								$newOverlapRange2 = TRUE;
								foreach ($overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"] as $keyOverlap => $overlapRange) {
									if (($overlapRange["start"] < $overlap_end) and ($overlapRange["end"] > $overlap_start)) {
										$overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"][($keyOverlap)]["count"]++;
										if ($overlapRange["start"] < $overlap_start) $overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"][($keyOverlap)]["start"] = $overlap_start;
										if ($overlapRange["end"] > $overlap_end) $overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"][($keyOverlap)]["end"] = $overlap_end;
										$newOverlapRange2 = FALSE;
			//							break;
									}
								}
								if ($newOverlapRange2) {
									array_push($overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"], array ("count" => 1,"start" => $overlap_start, "end" => $overlap_end));
								}
							}
						}
					}
					}
					// determine the maximum overlaps for the current overlap block
					foreach ($overlap_array[($ol_start_date)][($loopBlockKey)]["overlapRanges"] as $overlapRange) {
						if ($overlapRange["count"] > $maxOverlaps) $maxOverlaps = $overlapRange["count"];
					}
					$overlap_array[($ol_start_date)][($loopBlockKey)]["maxOverlaps"] = $maxOverlaps;
					foreach ($overlap_array[($ol_start_date)][($loopBlockKey)]["events"] as $updMasterEvent) {
						//if (($updMasterEvent["time"] != $newMasterTime) or ($updMasterEvent["key"] != $newMasterEventKey)) {
						if (($updMasterEvent["time"] != $newMasterTime) or ($updMasterEvent["key"] != $ol_uid)) {
							$master_array[($ol_start_date)][($updMasterEvent["time2"])][($updMasterEvent["key"])]["event_overlap"] = $maxOverlaps;
						}
					}
					$newEventAdded = TRUE;
					break;
				}
			}
		}

		if (!$newEventAdded) {
			if (isset($master_array[($ol_start_date)])) {
				foreach ($master_array[($ol_start_date)] as $keyTime => $eventTime) {
					foreach ($eventTime as $keyEvent => $event) {
						if ($keyTime != '-1') $entryDrawTimes =  drawEventTimes($event["event_start"], $event["event_end"]);

						if ((isset($entryDrawTimes["draw_start"]) && isset($entryDrawTimes["draw_end"]) && isset($drawTimes["draw_end"]) && isset($drawTimes["draw_start"])) && ($entryDrawTimes["draw_start"] < $drawTimes["draw_end"]) and ($entryDrawTimes["draw_end"] > $drawTimes["draw_start"])) {
							// define start time of overlap range and overlap block
							if ($entryDrawTimes["draw_start"] < $drawTimes["draw_start"]) {
								$overlap_start = $drawTimes["draw_start"];
								$overlapBlock_start = $entryDrawTimes["draw_start"];
							} else {
								$overlap_start = $entryDrawTimes["draw_start"];
								$overlapBlock_start = $drawTimes["draw_start"];
							}
							// define end time of overlap range and overlap block
							if ($entryDrawTimes["draw_end"] > $drawTimes["draw_end"]) {
								$overlap_end = $drawTimes["draw_end"];
								$overlapBlock_end = $entryDrawTimes["draw_end"];
							} else {
								$overlap_end = $entryDrawTimes["draw_end"];
								$overlapBlock_end = $drawTimes["draw_end"];
							}
							if (!isset($newBlockKey)) {
								// $overlap_array[($ol_start_date)][] = array ("blockStart" => $overlapBlock_start, "blockEnd" => $overlapBlock_end, "maxOverlaps" => 1, "events" => array (array ("time" => $keyTime, "key" => $keyEvent), array ("time" => $newMasterTime, "key" => $newMasterEventKey)), "overlapRanges" => array (array ("count" => 1, "start" => $overlap_start, "end" => $overlap_end)));
								$overlap_array[($ol_start_date)][] = array ("blockStart" => $overlapBlock_start, "blockEnd" => $overlapBlock_end, "maxOverlaps" => 1, "events" => array (array ("time" => $keyTime, "time2" => $keyTime,"key" => $keyEvent), array ("time" => $newMasterTime, "time2" => $realMasterTime,"key" => $ol_uid)), "overlapRanges" => array (array ("count" => 1, "start" => $overlap_start, "end" => $overlap_end)));
								$maxOverlaps = 1;
								end($overlap_array[($ol_start_date)]);
								$newBlockKey = key($overlap_array[($ol_start_date)]);
							} else {
								if ($overlap_array[($ol_start_date)][($newBlockKey)]["blockStart"] > $overlapBlock_start) $overlap_array[($ol_start_date)][($newBlockKey)]["blockStart"] = $overlapBlock_start;
								if ($overlap_array[($ol_start_date)][($newBlockKey)]["blockEnd"] < $overlapBlock_end) $overlap_array[($ol_start_date)][($newBlockKey)]["blockEnd"] = $overlapBlock_end;
								$overlap_array[($ol_start_date)][($newBlockKey)]["events"][] = array ("time" => $keyTime, "time2" => $keyTime, "key" => $keyEvent);
								$overlap_array[($ol_start_date)][($newBlockKey)]["overlapRanges"][] = array ("count" => 1, "start" => $overlap_start, "end" => $overlap_end);
							}
							// update master_array
							$master_array[($ol_start_date)][($keyTime)][($keyEvent)]["event_overlap"] = $maxOverlaps;
						}
					}
				}
			}
		}

// for debugging the checkOverlap function
//print 'Date: ' . $ol_start_date . ' / New Time: ' . $newMasterTime . ' / New Key: ' . $newMasterEventKey . '<br />';
//print '<pre>';
//print_r($overlap_array);
//print '</pre>';

	return $maxOverlaps;
}

// drei 20021126: function for checking and removing overlapping events
function removeOverlap($ol_start_date, $ol_start_time, $ol_key = 0) {
	global $master_array, $overlap_array;

	if (sizeof($overlap_array[$ol_start_date]) > 0) {
		$ol_end_time = $master_array[$ol_start_date][$ol_start_time][$ol_key]["event_end"];
		foreach ($overlap_array[$ol_start_date] as $keyBlock => $blockId) {
			if (($blockId["blockStart"] <= $ol_start_time) or ($blockId["blockEnd"] >= $ol_start_time)) {
				foreach ($blockId["events"] as $keyEvent => $ol_event) {
					$master_array[$ol_start_date][$ol_event["time"]][$ol_event["key"]]["event_overlap"] -= 1;
					if (($ol_event["time"] == $ol_start_time) and ($ol_event["key"] == $ol_key)) {
						unset ($overlap_array[$ol_start_date][$keyBlock]["events"][$keyEvent]);
					}
				}
				if ($blockId["maxOverlaps"] = 1) {
					unset ($overlap_array[$ol_start_date][$keyBlock]);
				} else {
					$blockId["maxOverlaps"] -= 1;
				}
			}
		}
	}
}

function drawEventTimes ($start, $end) {
	global $gridLength;
	
	ereg ("([0-9]{2})([0-9]{2})", $start, $time);
	$sta_h = $time[1];
	$sta_min = $time[2];
	$sta_min = sprintf("%02d", floor($sta_min / $gridLength) * $gridLength);
	if ($sta_min == 60) {
		$sta_h = sprintf("%02d", ($sta_h + 1));
		$sta_min = "00";
	}
	
	ereg ("([0-9]{2})([0-9]{2})", $end, $time);
	$end_h = $time[1];
	$end_min = $time[2];
	$end_min = sprintf("%02d", floor($end_min / $gridLength) * $gridLength);
	if ($end_min == 60) {
		$end_h = sprintf("%02d", ($end_h + 1));
		$end_min = "00";
	}
	
	if (($sta_h . $sta_min) == ($end_h . $end_min))  {
		$end_min += $gridLength;
		if ($end_min == 60) {
			$end_h = sprintf("%02d", ($end_h + 1));
			$end_min = "00";
		}
	}
	
	$draw_len = ($end_h * 60 + $end_min) - ($sta_h * 60 + $sta_min);
	
	return array ("draw_start" => ($sta_h . $sta_min), "draw_end" => ($end_h . $end_min), "draw_length" => $draw_len);
}

// word wrap function that returns specified number of lines
// when lines is 0, it returns the entire string as wordwrap() does it
function word_wrap($str, $length, $lines=0) {
	if ($lines > 0) {
		$len = $length * $lines;
		if ($len < strlen($str)) {
			$str = substr($str,0,$len).'...';
		}
	}
	return $str;
}


function strtotime2($str,$myint=-1) {
  if ($myint==-1) {
    if (strlen($str)==4) {
      $str = date("m/d/y")." ".substr($str,0,2).":".substr($str,2,2);
    }
    $result = strtotime($str);
    if ($result==-1) {
      return strtotime(str_replace("24:00","00:00",$str));
    } else {
      return $result;
    }
  } else {
    $result = strtotime($str,$myint);
    if ($result==-1) {
      return strtotime(str_replace("2400","0000",$str),$myint);
    } else {
      return $result;
    }
  }
}

function str_date_to_int($str_date) {
  return substr($str_date,0,2)*3600+substr($str_date,2,2)*60;
}

function checkdir($dirname,$htaccess) {
  global $hashmap;
  
  error_reporting (E_ERROR | E_PARSE);
  if (!is_dir($dirname)) {
    $dirname2 = $dirname;
	if ($dirname2[strlen($dirname2)-1]=="/") $dirname2 = substr($dirname2,0,-1);
	$dirname2 = substr($dirname2,0,strrpos($dirname2,"/"));
    if (is_writeable($dirname2)) {
      mkdir($dirname,0777);
    } else {die($hashmap["index_att_dir_does_not_exist"]." ".$dirname);}
  }
  if (!is_writeable($dirname)) {
    die($hashmap["index_att_dir_does_not_exist"]." ".$dirname);
  }
  if (!file_exists($dirname."index.htm")) {
    $fd = fopen($dirname."index.htm", "w");
    fwrite($fd, "You are not allowed to view this folder.");
    fclose($fd);
  }
  if (!file_exists($dirname."index.html")) {
    $fd = fopen($dirname."index.html", "w");
    fwrite($fd, "You are not allowed to view this folder.");
    fclose($fd);
  }
  if ($htaccess and !file_exists($dirname.".htaccess")) {
    $fd = fopen($dirname.".htaccess", "w");
    fwrite($fd, "Order deny,allow\nDeny from all\n");
	// AuthName \"MoreGroupWare Store - No Access\"\nAuthType Basic\nrequire mgw\n");
    fclose($fd);
  } elseif (!$htaccess and file_exists($dirname.".htaccess")) {
    unlink($dirname.".htaccess");
  }
  error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

}

function htmlnonspecialchars($strvar) {
  $strvar=ereg_replace('&gt;', '>', $strvar);
  $strvar=ereg_replace('&lt;', '<', $strvar);
  $strvar=ereg_replace('&quot;', "\"", $strvar);
  $strvar=ereg_replace('&amp;', '&', $strvar);
  return $strvar;
}

function get_group_name($groupid) {
  global $conn;

  $sql = "SELECT name FROM mgw_groups where id=".(int)$groupid;
  if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  $row2 = $res2->FetchRow();
	  
  if (isset($row2["name"]) and $row2["name"]!="") return $row2["name"];
    else return "_";
}


function preview_from_file($filename,$calendar_name) {
  global $hashmap,$tz_array,$conn;
  $cal_entries = array();

  if (strpos($filename,"://") or strpos("@".$filename,"holidays/")==1 or (isset($_SESSION["calendar2_preview"]) and $_SESSION["calendar2_preview"]!="") or (isset($_SESSION["calendar2_preview2"]) and $_SESSION["calendar2_preview2"]!="")) {
    if (isset($_GET["debug"]) and $_SESSION["MGW"]->username=="admin") {
	  echo "<pre>";readfile($filename);echo "</pre>";
	}
	if (strpos($filename,"://")) {
	  $filename2 = CACHE_FOLDER.basename($filename);
	  if ((file_exists($filename2) and (time() > filemtime($filename2)+86400)) or !file_exists($filename2)) {
	    $return = "";
    	if ($fp = fopen($filename, 'rb')) {
		  while (!feof($fp)) {
    		$return .= fread($fp, 1024);
    	  }
    	  fclose($fp);
        }
    	if ($fp = fopen($filename2, 'w')) {
		  fwrite($fp,$return);
    	  fclose($fp);
        }
	  }
	  $filename = $filename2;
	}
	
	$ifile = fopen($filename, "r");
	if ($ifile == FALSE) exit($hashmap["error_invalidcal_lang"]." ".$filename);
	$nextline = fgets($ifile, 1024);
	while (str_replace(array("\n","\r"),"",$nextline)=="") $nextline = fgets($ifile, 1024);
	if (trim($nextline) != 'BEGIN:VCALENDAR') exit($hashmap["error_invalidcal_lang"]." ".$filename);

	$begin = false;
	while (!feof($ifile)) {
	  $line = $nextline;
	  $nextline = fgets($ifile, 1024);
	  $nextline = ereg_replace("[\r\n]", "", $nextline);
	  while (substr($nextline, 0, 1) == " ") {
		$line = $line . substr($nextline, 1);
		$nextline = fgets($ifile, 1024);
		$nextline = ereg_replace("[\r\n]", "", $nextline);
	  }
	  $line = trim($line);
	  if ($line == 'END:VEVENT') {
	    $begin = false;
	    if ($summary!="") {
		
		  $native_uid = 0;
		  if (((is_numeric($uid) and $uid!=0) or ($uid!="")) and strpos("@".$uid,md5($_SERVER["HTTP_HOST"]))==1) {
			$native_uid=str_replace(md5($_SERVER["HTTP_HOST"]),"",$uid);

		    $sql = "select id from mgw_calendar2_ics where c_duser_id=".(int)$_SESSION["MGW"]->userid." and id=".(int)$native_uid;
		    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
	        $row = $res->FetchRow();
		    
			if (!isset($row["id"]) or $row["id"]=="") $native_uid = 0;
		  }
		  
	      if (!isset($start_time) or $start_time=="") {
		    if ($end_date == "") $end_date = date("Ymd",strtotime2($start_date)+(24*3600));
			$start_unixtime = strtotime2($start_date);
		  } else {
		    $start_date = date("Ymd",$start_unixtime)."T".date("His",$start_unixtime);
		    $end_date = date("Ymd",$end_unixtime)."T".date("His",$end_unixtime);
		  }
		  
		  $drep_exdate = "";
		  if (isset($except_dates) and count($except_dates)>0) {
		    $drep_exdate = implode($except_dates,",");
		  }
		
		  $drep_freq = "";
		  $drep_until = "";
		  $drep_byday="";
		  $drep_count = 0;
		  $drep_interval = 0;
		  if (is_array($rrule_array) and count($rrule_array)>0) {
		    if (isset($rrule_array["FREQ"])) {
		      switch (strtolower($rrule_array["FREQ"])) {
			    case "yearly":
			      $drep_freq = strtolower($rrule_array["FREQ"]);
			      $drep_interval = 1;
			      break;
			    case "monthly":
			      $drep_freq = strtolower($rrule_array["FREQ"]);
			      $drep_interval = 1;
			      break;
			    case "daily":
			      $drep_freq = strtolower($rrule_array["FREQ"]);
			      $drep_interval = 1;
			      break;
			    case "weekly":
			      $drep_freq = strtolower($rrule_array["FREQ"]);
				  if (isset($rrule_array["BYDAY"])) $drep_byday=$rrule_array["BYDAY"];
			      $drep_interval = 1;
			    break;
			  }
		    }
		    if ($drep_freq!="" and isset($rrule_array["INTERVAL"]) and is_numeric($rrule_array["INTERVAL"])) {
		      $drep_interval = $rrule_array["INTERVAL"];
		    }
		    if ($drep_freq!="" and isset($rrule_array["COUNT"]) and is_numeric($rrule_array["COUNT"])) {
		      $drep_count = $rrule_array["COUNT"];
		    }
			if ($drep_freq!="" and isset($rrule_array["UNTIL"]) and $rrule_array["UNTIL"]!="") {
			  $drep_until = $rrule_array["UNTIL"];
			}
		  }

    	  $cal_entries[$start_date][] = array(
	  	    "dstart" => $start_date,
            "dend" => $end_date,
            "dsummary" => $summary,
            "dlocation" => $location,
            "dhomepage" => $homepage,
            "ddesc" => trim($description,"<br>"),
            "dclass" => $class,
            "drep_freq" => $drep_freq,
            "drep_until" => $drep_until,
            "drep_count" => $drep_count,
            "drep_interval" => $drep_interval,
            "drep_days" => strtolower($drep_byday),
            "dsequence" => ($sequence==""?0:$sequence),
            "drep_exdate" => $drep_exdate,
            "dcategories" => $categories,
            "dorganizer" => $organizer,
            "dattendee" => $attendee,
            "dattendee_non" => $attendee_non,
            "doptional" => $optional,
            "dcalendar" => $calendar_name,
            "c_duser_id" => $_SESSION["MGW"]->userid,
            "duser_id" => 0, // $_SESSION["MGW"]->userid
			"start_unixtime" => $start_unixtime,
			"dtstamp_unixtime" => $dtstamp_unixtime,
			"native_uid" => $native_uid,
            "dstatus" => $status,
			"state" => $state,
		    "id" => ((is_numeric($uid) and $uid==0)?0:$uid)
	      );
	    }
	  
	  } elseif ($line == 'BEGIN:VEVENT') {
		$begin = true;
	    unset (
		  $valarm_description, $the_duration, 
		  
		  $allday_start, $allday_end,	$start, $end,
		  $start_time, $end_time,	$start_date, 
		  $until, $bymonth, $byday, $bymonthday, $byweek, $byweekno, 
		  $byminute, $byhour, $bysecond, $byyearday, $bysetpos, $wkst,
		  $interval, $number
	    );
		
		$recurrence_d = "";
		$end_date = "";
		$sequence = "";
		$summary = "";
		$description = "";
		$location = "";
		$status = "";
		$homepage = "";
		$class = "";
		$categories = "";
		$rrule_array = "";
		$start_unixtime = 0;
		$dtstamp_unixtime = 0;
		$end_unixtime = 0;
		$uid = 0;
		$attendee = "";
		$organizer = "";
		$attendee_non = "";
		$optional = "";
						
	    $except_dates = array();
	    $except_times = array();
		$state = array();
	    $first_duration = TRUE;
	    $count = 1000000;
	    $valarm_set = FALSE;
			
	  } elseif ($begin) {
	    unset ($field, $data, $prop_pos, $property);
	    ereg ("([^:]+):(.*)", $line, $line);
	    if (is_array($line)) {
		  $field = $line[1];
  		  $data = $line[2];
	    } else {
		  $field = "";
		  $data = "";
	    }
			
	    $property = $field;
	    $prop_pos = strpos($property,';');
	    if ($prop_pos !== false) $property = substr($property,0,$prop_pos);
	    $property = strtoupper($property);
	    switch ($property) {

				case 'UID':
					$uid = strip_tags($data);
					break;
				case 'DTSTART':
					$zulu_time = false;
					if (substr($data,-1) == 'Z') $zulu_time = true;
					$data = ereg_replace('T', '', $data);
					$data = ereg_replace('Z', '', $data);
					$field = ereg_replace(';VALUE=DATE-TIME', '', $field); 
					if (preg_match("/^DTSTART;VALUE=DATE/i", $field))  {
						$allday_start = $data;
						$start_date = $allday_start;
					} else {
						if (preg_match("/^DTSTART;TZID=/i", $field)) {
							$tz_tmp = explode('=', $field);
							$tz_dtstart = $tz_tmp[1];
							unset($tz_tmp);
						} elseif ($zulu_time) {
							$tz_dtstart = 'GMT';
						}

						ereg ('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})', $data, $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]);

						$dlst = date('I', $start_unixtime);
						$server_offset_tmp = chooseOffset($start_unixtime);
						if (isset($tz_dtstart)) {
							if (array_key_exists($tz_dtstart, $tz_array)) {
								$offset_tmp = $tz_array[$tz_dtstart][$dlst];
							} else {
								$offset_tmp = $tz_array["Same as Server"][$dlst];
							}
						} elseif (isset($calendar_tz)) {
							if (array_key_exists($calendar_tz, $tz_array)) {
								$offset_tmp = $tz_array[$calendar_tz][$dlst];
							} else {
							$offset_tmp = $tz_array["Same as Server"][$dlst];
							}
						} else {
							$offset_tmp = $server_offset_tmp;
						}
						$start_unixtime = calcTime($offset_tmp, $server_offset_tmp, $start_unixtime);
						$start_date = date('Ymd', $start_unixtime);
						$start_time = date('Hi', $start_unixtime);
						unset($server_offset_tmp);
					}
					break;
					
				case 'DTSTAMP':
					$zulu_time = false;
					if (substr($data,-1) == 'Z') $zulu_time = true;
					$data = ereg_replace('T', '', $data);
					$data = ereg_replace('Z', '', $data);
					$field = ereg_replace(';VALUE=DATE-TIME', '', $field); 

						if (preg_match("/^DTSTART;TZID=/i", $field)) {
							$tz_tmp = explode('=', $field);
							$tz_dtstart = $tz_tmp[1];
							unset($tz_tmp);
						} elseif ($zulu_time) {
							$tz_dtstart = 'GMT';
						}
		
						ereg ('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})', $data, $regs);
						$dtstamp_unixtime = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);

						$dlst = date('I', $dtstamp_unixtime);
						$server_offset_tmp = chooseOffset($dtstamp_unixtime);
						if (isset($tz_dtstart)) {
							if (is_array($tz_array) and array_key_exists($tz_dtstart, $tz_array)) {
								$offset_tmp = $tz_array[$tz_dtstart][$dlst];
							} else {
								$offset_tmp = $tz_array["Same as Server"][$dlst];
							}
						} elseif (isset($calendar_tz)) {
							if (array_key_exists($calendar_tz, $tz_array)) {
								$offset_tmp = $tz_array[$calendar_tz][$dlst];
							} else {
							$offset_tmp = $tz_array["Same as Server"][$dlst];
							}
						} else {
							$offset_tmp = $server_offset_tmp;
						}
						$dtstamp_unixtime = calcTime($offset_tmp, $server_offset_tmp, $dtstamp_unixtime);
						unset($server_offset_tmp);

					break;
					
				case 'DTEND';
					$zulu_time = false;
					if (substr($data,-1) == 'Z') $zulu_time = true;
					$data = ereg_replace('T', '', $data);
					$data = ereg_replace('Z', '', $data);
					$field = ereg_replace(';VALUE=DATE-TIME', '', $field); 
					if (preg_match("/^DTEND;VALUE=DATE/i", $field))  {
						$allday_end = $data;
					} else {
						if (preg_match("/^DTEND;TZID=/i", $field)) {
							$tz_tmp = explode('=', $field);
							$tz_dtend = $tz_tmp[1];
							unset($tz_tmp);
						} elseif ($zulu_time) {
							$tz_dtend = 'GMT';
						}
						
						ereg ('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})', $data, $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]);
		
						$dlst = date('I', $end_unixtime);
						$server_offset_tmp = chooseOffset($end_unixtime);
						if (isset($tz_dtend)) {
						  if (array_key_exists($tz_dtend, $tz_array)) {
							$offset_tmp = $tz_array[$tz_dtend][$dlst];
						  } else {
							$offset_tmp = $tz_array["Same as Server"][$dlst];
						  }
						} elseif (isset($calendar_tz)) {
						  if (array_key_exists($calendar_tz, $tz_array)) {
							$offset_tmp = $tz_array[$calendar_tz][$dlst];
						  } else {
							$offset_tmp = $tz_array["Same as Server"][$dlst];
						  }
						} else {
							$offset_tmp = $server_offset_tmp;
						}
						$end_unixtime = calcTime($offset_tmp, $server_offset_tmp, $end_unixtime);
						$end_date = date('Ymd', $end_unixtime);
						$end_time = date('Hi', $end_unixtime);
						unset($server_offset_tmp);
		
					}
					break;
					
				case 'EXDATE':
					$data = split(",", $data);
					foreach ($data as $exdata) {
						$exdata = ereg_replace('T', '', $exdata);
						$exdata = ereg_replace('Z', '', $exdata);
						ereg ('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})', $exdata, $regs);
						$except_dates[] = $regs[1] . $regs[2] . $regs[3];
						$except_times[] = $regs[4] . $regs[5];
					}
					break;
					
				case 'SUMMARY':
					$data = str_replace("\\n", "<br>", strip_tags(utf8_decode($data)));
					$data = str_replace("\\r", "<br>", $data);
					// $data = htmlentities(urlencode($data));
					if ($valarm_set == FALSE) { 
						$summary = $data;
					} else {
						$valarm_summary = $data;
					}
					break;
					
				case 'STATUS':
					$data = str_replace("\\n", "<br>", strip_tags($data));
					$data = str_replace("\\r", "<br>", $data);
					$status = strtolower($data);
					break;
					
				case 'DESCRIPTION':
					$data = str_replace(array("\\n","\\"), array("<br>",""), modify_html(utf8_decode(" ".$data)));
					$data = str_replace("\\r", "<br>", $data);
					// $data = htmlentities(urlencode($data));
					if ($valarm_set == FALSE) { 
						$description = $data;
					} else {
						$valarm_description = $data;
					}
					break;
					
				case 'LOCATION':
				    $full_str = $field.":".$data;
					if (strpos(strtolower($full_str),"altrep")) {

	    			  eregi ("altrep=\"(.*)\"", $full_str,$line2);
				      if (is_array($line2)) {
						$homepage = str_replace(array("\\n","\\r"),"",$line2[1]);
						eregi ("altrep=\".*\":(.*)", $full_str,$line2);
					    if (is_array($line2)) {
						  $data = $line2[1];
						}
					  }
					}
					$data = str_replace("\\n", "<br>", strip_tags(utf8_decode($data)));
					$data = str_replace("\\r", "<br>", $data);
					// $data = htmlentities(urlencode($data));
					if ($valarm_set == FALSE) { 
						$location = $data;
					} else {
						$valarm_location = $data;
					}
					break;
					
				case 'CATEGORIES':
					$data = str_replace("\\n", "<br>", strip_tags($data));
					$data = str_replace("\\r", "<br>", $data);
					// $data = htmlentities(urlencode($data));
					if ($valarm_set == FALSE) { 
						$categories = $data;
					} else {
						$valarm_categories = $data;
					}
					break;
					
				case 'CLASS':
                  $data = str_replace("\\n", "<br>", $data);
				  $data = str_replace("\\r", "<br>", $data);
				  $data = strtolower($data);
				  if ($data=="public" or $data=="private" or $data=="confidential") {
				    if ($valarm_set == FALSE) { 
					  $class = $data;
				    } else {
					  $valarm_class = $data;
				    }
				  }
				  break;

				case 'SEQUENCE':
				  if (is_numeric($data)) $sequence = $data;				  
				  break;

				case 'X-WR-TIMEZONE':
					$calendar_tz = $data;
					$master_array['calendar_tz'] = $calendar_tz;
					break;
				case 'DURATION':
					if (($first_duration == TRUE) && (!stristr($field, '=DURATION'))) {
						ereg ('^P([0-9]{1,2})?([W,D]{0,1}[T])?([0-9]{1,2}[H])?([0-9]{1,2}[M])?([0-9]{1,2}[S])?', $data, $duration);
						if ($duration[2] = 'W') {
							$weeks = $duration[1];
							$days = 0;
						} else {
							$days = $duration[1];
							$weeks = 0;
						}
						$hours = ereg_replace('H', '', $duration[3]);
						$minutes = ereg_replace('M', '', $duration[4]);
						$seconds = ereg_replace('S', '', $duration[5]);
						$the_duration = ($weeks * 60 * 60 * 24 * 7) + ($days * 60 * 60 * 24) + ($hours * 60 * 60) + ($minutes * 60) + ($seconds);
						$end_unixtime = $start_unixtime + $the_duration;
						$end_time = date ('Hi', $end_unixtime);
						$first_duration = FALSE;
					}	
					break;
				case 'RRULE':
					$data = ereg_replace ('RRULE:', '', $data);
					$rrule = split (';', $data);
					foreach ($rrule as $recur) {
						ereg ('(.*)=(.*)', $recur, $regs);
						$rrule_array[$regs[1]] = $regs[2];
					}
					break;
				case 'ATTENDEE':
					eregi ('^mailto:(.*)', $data, $regs);
					eregi (';partstat=(.*);r', $field, $regs2);
					if (is_array($regs)) $data = strtolower(trim($regs[1]));
					if ($data!="" and is_array($regs2)) $state[$data] = strtolower(trim($regs2[1]));
					
				    if ($data!="") {
					  if (strpos(strtoupper($field),"OPT-PARTICIPANT")) {
					    if (strpos("@".$attendee_non,$data)==0) {
					      if ($attendee_non!="") $attendee_non .=", ";
					      $attendee_non .= $data;
						}
					  } elseif (strpos(strtoupper($field),"NON-PARTICIPANT")) {
					    if (strpos("@".$optional,$data)==0) {
					      if ($optional!="") $optional .=", ";
					      $optional .= $data;
						}
					  }	else {
					    if (strpos("@".$attendee,$data)==0) {
					      if ($attendee!="") $attendee .=", ";
					      $attendee .= $data;
						}
					  }
					}
					break;
				case 'ORGANIZER':
					eregi ('^mailto:(.*)', $data, $regs);
					eregi (';partstat=(.*);r', $field, $regs2);
					if (is_array($regs)) $data = strtolower(trim($regs[1]));
					if ($data!="" and is_array($regs2)) $state[$data] = strtolower(trim($regs2[1]));
					
				    if ($data!="" and strpos("@".$organizer,$data)==0) {
					  if ($organizer!="") $organizer .= ", ";
					  $organizer .= $data;
					}
					break;
	    }
	  }
    }
  }
  return $cal_entries;
}

function create_holiday_calendar($import_cal_name,$calendar_rights) {
  global $conn;

  $sql = "select id from mgw_calendar2_cals where dcalendar=".$conn->Quote("#".$import_cal_name);
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  $cal_count = $res->RecordCount();

  if ($cal_count==0) {
    $id = mgw_genID('mgw__seq_cals',2);
    $sql = "INSERT INTO mgw_calendar2_cals (id,dcalendar) VALUES (".(int)$id.",".$conn->Quote("#".$import_cal_name).")";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    foreach ($calendar_rights as $item=>$temp_val) {	

	  $sql = "select id from mgw_rights2 where id_string=".$conn->Quote("root_modules_calendar2_holidaycalendars_".$import_cal_name."_".$item);
	  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	  $cal_count = $res->RecordCount();

	  if ($cal_count==0) {
    	$sql = "INSERT INTO mgw_rights2 (id, id_string, allow_users, deny_users, allow_groups, deny_groups, cuser, cdate, default_value) VALUES (".(int)mgw_genID('mgw__seq_rights2').", ".$conn->Quote("root_modules_calendar2_holidaycalendars_".$id."_".$item).", ',".(int)$_SESSION["MGW"]->userid.",', ',,', ',,', ',,', ".(int)$_SESSION["MGW"]->userid.", ".time().", 0);";
	    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	  }
    }
  }
}

function pump_into_sql($file,$import_cal_name) {
  global $conn;
  
  $sdate=getDate(time());
  $now = $sdate["year"].twodigit($sdate["mon"]).twodigit($sdate["mday"])."T".twodigit($sdate["hours"]).twodigit($sdate["minutes"]).twodigit($sdate["seconds"]);

  $cal_entries = preview_from_file($file,$import_cal_name);

  if (is_array($cal_entries) and count($cal_entries)>0) {
	foreach ($cal_entries as $tmp_entry) {
      foreach ($tmp_entry 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("public").",".$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__));
	  }
	}
  }
}

?>