function churchresource_getCurrentBookings()
{
    $txt = "";
    if (user_access("view", "churchresource")) {
        include_once "churchresource_db.php";
        // Alle buchungen ab jetzt bis morgen mit Status 2
        $res = getBookings(0, 1, "2");
        if ($res != null) {
            $arr = array();
            $counter = 0;
            foreach ($res as $r) {
                $r->startdate = new DateTime($r->startdate);
                $r->enddate = new DateTime($r->enddate);
                $ds = getAllDatesWithRepeats($r, 0, 1);
                if ($ds != null) {
                    foreach ($ds as $d) {
                        $counter = $counter + 1;
                        $a = array();
                        $a["realstart"] = new DateTime($d->format('Y-m-d H:i:s'));
                        $a["startdate"] = $r->startdate;
                        $a["enddate"] = $r->enddate;
                        $a["person_name"] = $r->person_name;
                        $a["resource_id"] = $r->resource_id;
                        $a["repeat_id"] = $r->repeat_id;
                        $a["text"] = $r->text;
                        $a["id"] = $r->id;
                        $arr[] = $a;
                    }
                }
            }
            if ($arr != null) {
                $resources = churchcore_getTableData("cr_resource");
                function cmp($a, $b)
                {
                    if ($a["realstart"] == $b["realstart"]) {
                        return 0;
                    } else {
                        if ($a["realstart"] > $b["realstart"]) {
                            return 1;
                        } else {
                            -1;
                        }
                    }
                }
                usort($arr, "cmp");
                foreach ($arr as $val) {
                    $txt .= "<li><p><a href=\"?q=churchresource&id=" . $val["id"] . "\">" . $val["text"] . "</a> ";
                    if ($val["repeat_id"] > 0) {
                        $txt .= '<img title="Serie startet vom ' . $val["startdate"]->format('d.m.Y H:i') . '" src="' . CHURCHRESOURCE . '/images/recurring.png" width="16px"/> ';
                    }
                    $txt .= "(" . $resources[$val["resource_id"]]->bezeichnung . ")<br/><small>" . $val["realstart"]->format('d.m.Y H:i') . " " . $val["person_name"] . "</small><br/>";
                }
                if ($txt != "") {
                    $txt = "<ul>{$txt}</ul>";
                }
            }
        }
    }
    return $txt;
}
function churchcal__ical()
{
    global $base_url, $config;
    include_once CHURCHCAL . "/churchcal_db.php";
    drupal_add_http_header('Content-Type', 'text/calendar;charset=utf-8', false);
    drupal_add_http_header('Content-Disposition', 'inline;filename="ChurchTools.ics"', false);
    drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', false);
    drupal_add_http_header('Cache-Control', 'private', true);
    $content = drupal_get_header();
    $cat_names = null;
    if (isset($_GET["security"]) && isset($_GET["id"])) {
        $db = db_query("select * from {cc_calcategory} where id=:id and randomurl=:randomurl", array(":id" => $_GET["id"], ":randomurl" => $_GET["security"]))->fetch();
        if ($db != false) {
            $cat_names[$_GET["id"]] = new stdClass();
            $cat_names[$_GET["id"]]->bezeichnung = $db->bezeichnung;
            $cats = array(0 => $_GET["id"]);
        }
    }
    if ($cat_names == null) {
        $cats = churchcal_getAllowedCategories(false, true);
        $cat_names = churchcal_getAllowedCategories(false, false);
    }
    $arr = churchcal_getCalPerCategory(array("category_ids" => $cats), false);
    $txt = "";
    foreach ($arr as $cats) {
        foreach ($cats as $res) {
            $res->startdate = new DateTime($res->startdate);
            $res->enddate = new DateTime($res->enddate);
            $diff = $res->enddate->format("U") - $res->startdate->format("U");
            $subid = 0;
            foreach (getAllDatesWithRepeats($res, -90, 400) as $d) {
                $txt .= "BEGIN:VEVENT\r\n";
                $txt .= "ORGANIZER:MAILTO:" . variable_get('site_mail', '') . "\r\n";
                $txt .= "SUMMARY:" . $res->bezeichnung . "\r\n";
                //$txt.="X-MICROSOFT-CDO-BUSYSTATUS:BUSY\r\n";
                if ($res->link != "") {
                    $txt .= "URL:" . $res->link . "\r\n";
                } else {
                    $txt .= "URL:" . $base_url . "?q=churchcal\r\n";
                }
                if ($res->ort != "") {
                    $txt .= "LOCATION:" . $res->ort . "\r\n";
                }
                $subid++;
                $txt .= "UID:" . $res->id . "_{$subid}\r\n";
                $txt .= "DTSTAMP:" . churchcore_stringToDateICal($res->modified_date) . "\r\n";
                $ts = $diff + $d->format("U");
                //$enddate=new DateTime("@$ts");
                $enddate = clone $d;
                $enddate->modify("+{$diff} seconds");
                // Ganztagestermin
                if ($res->startdate->format('His') == "000000" && $res->enddate->format('His') == "000000") {
                    $txt .= "DTSTART;VALUE=DATE:" . $d->format('Ymd') . "\r\n";
                    $txt .= "DTEND;VALUE=DATE:" . date('Ymd', strtotime('+1 day', $enddate->format("U"))) . "\r\n";
                } else {
                    $txt .= "DTSTART:" . $d->format('Ymd\\THis') . "\r\n";
                    $txt .= "DTEND:" . $enddate->format('Ymd\\THis') . "\r\n";
                }
                $txt .= 'DESCRIPTION:Kalender:' . $cat_names[$res->category_id]->bezeichnung . ' - Cal[' . $res->id . '] - ' . $res->notizen . "\r\n";
                $txt .= "END:VEVENT\r\n";
            }
        }
    }
    echo surroundWithVCALENDER($txt);
}
/**
 * use template for calendar entries, include text added by surroundWithVCALENDER
 */
function churchcal__ical()
{
    global $base_url, $config;
    include_once CHURCHCAL . "/churchcal_db.php";
    drupal_add_http_header('Content-Type', 'text/calendar;charset=utf-8', false);
    drupal_add_http_header('Content-Disposition', 'inline;filename="ChurchTools.ics"', false);
    drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', false);
    drupal_add_http_header('Cache-Control', 'private', true);
    $content = drupal_get_header();
    $catNames = null;
    if (($security = getVar("security")) && ($id = getVar("id"))) {
        $db = db_query("SELECT * FROM {cc_calcategory}\n                    WHERE id=:id AND randomurl=:randomurl", array(":id" => $id, ":randomurl" => $security))->fetch();
        if ($db) {
            $catNames[$id] = new stdClass();
            $catNames[$id]->bezeichnung = $db->bezeichnung;
            $cats = array(0 => $id);
        }
    }
    if (!$catNames) {
        $cats = churchcal_getAllowedCategories(false, true);
        $catNames = churchcal_getAllowedCategories(false, false);
    }
    $arr = churchcal_getCalPerCategory(array("category_ids" => $cats), false);
    $txt = "";
    foreach ($arr as $cats) {
        foreach ($cats as $res) {
            $res->startdate = new DateTime($res->startdate);
            $res->enddate = new DateTime($res->enddate);
            $diff = $res->enddate->format("U") - $res->startdate->format("U");
            // TODO: use DateTime function like next line?
            //     $diff = $res->enddate->diff($res->startdate);
            $subid = 0;
            foreach (getAllDatesWithRepeats($res, -90, 730) as $d) {
                $txt .= "BEGIN:VEVENT" . NL;
                $txt .= "ORGANIZER:MAILTO:" . getConf('site_mail', '') . NL;
                $txt .= "SUMMARY:" . $res->bezeichnung . NL;
                //$txt.="X-MICROSOFT-CDO-BUSYSTATUS:BUSY" . NL;
                if ($res->link != "") {
                    $txt .= "URL:" . $res->link . NL;
                } else {
                    $txt .= "URL:" . $base_url . "?q=churchcal" . NL;
                }
                if ($res->ort != "") {
                    $txt .= "LOCATION:" . $res->ort . NL;
                }
                $subid++;
                $txt .= "UID:{$res->id}_{$subid}" . NL;
                $txt .= "DTSTAMP:" . churchcore_stringToDateICal($res->modified_date) . NL;
                $enddate = clone $d;
                $enddate->modify("+{$diff} seconds");
                // all day event
                if ($res->startdate->format('His') == "000000" && $res->enddate->format('His') == "000000") {
                    $txt .= "DTSTART;VALUE=DATE:" . $d->format('Ymd') . NL;
                    $txt .= "DTEND;VALUE=DATE:" . date('Ymd', strtotime('+1 day', $enddate->format("U"))) . NL;
                } else {
                    $txt .= "DTSTART:" . $d->format('Ymd\\THis') . NL;
                    $txt .= "DTEND:" . $enddate->format('Ymd\\THis') . NL;
                }
                $txt .= 'DESCRIPTION:Kalender:' . $catNames[$res->category_id]->bezeichnung;
                if (!empty($res->notizen)) {
                    $txt .= ' - ' . cleanICal($res->notizen);
                }
                $txt .= NL;
                $txt .= "END:VEVENT" . NL;
            }
        }
    }
    echo surroundWithVCALENDER($txt);
}
/**
 * called by ChurchCal on changes in calendar events
 * it uses old_startdate to move all events, then checks if there are events to create or delete
 * from changes in repeats, exceptions or additions
 * @param array $params
 * @param string $source
 */
function FromChurchCal($params, $csevent)
{
    echo "NOT USED ANYMORE FromChurchCal ";
    $diff = null;
    if (isset($params["old_startdate"])) {
        // move events to new startdate
        $startdate = new DateTime($params["startdate"]);
        $old_startdate = new DateTime($params["old_startdate"]);
        $diff = $startdate->format("U") - $old_startdate->format("U");
        db_query("UPDATE {cs_event} SET startdate = DATEADD(startdate, INTERVAL :diff SECOND)\n              WHERE e.cc_cal_id = :cal_id", array(":cal_id" => $params["cal_id"]));
    }
    // without repeat_id, this is only a time shift, so we can end processing here.
    if (empty($params["repeat_id"])) {
        return;
    }
    // Collect events into array to collect the info which has to be created/deleted/updated
    $events = array();
    // Get all mapped events from DB
    $db = db_query("SELECT id, startdate FROM {cs_event} e\n                  WHERE e.cc_cal_id=:cal_id", array(":cal_id" => $params["event"]["id"]));
    foreach ($db as $e) {
        $sd = new DateTime($e->startdate);
        $events[$sd->format('Y-m-d')] = array("status" => "delete", "id" => $e->id);
    }
    $o = _convertCTDateTimeToObjects($params);
    foreach (getAllDatesWithRepeats($o, -1000, +1000) as $d) {
        $sd = $d->format('Y-m-d');
        // Event was already moved above through old_startdate
        if (isset($events[$sd])) {
            $events[$sd]["status"] = "ok";
        } else {
            $events[$sd] = array("status" => "create");
        }
        $events[$sd]["startdate"] = $d->format('Y-m-d H:i:s');
    }
    $template = null;
    if (isset($params["eventTemplate"])) {
        $template = $params["eventTemplate"];
    }
    foreach ($events as $key => $do) {
        if ($do["status"] == "delete") {
            $params["id"] = $do["id"];
            $params["informDeleteEvent"] = 1;
            $params["deleteCalEntry"] = 0;
            churchservice_deleteEvent($params, $source);
        } else {
            if ($do["status"] == "create" && $template != null) {
                $params["startdate"] = $do["startdate"];
                $params["event"]["cc_cal_id"] = $params["event"]["id"];
                $params["eventTemplate"] = $template;
                churchservice_createEvent($params, $source);
            }
        }
    }
}
/**
 * is Day date (without Time) in $event
 * @param [type] $date
 * @param [type] $event
 */
function dateInCCEvent($date, $event)
{
    $ret = false;
    if ($event == null) {
        return false;
    }
    $ds = getAllDatesWithRepeats((object) $event, 0, 9999, new DateTime($event["startdate"]));
    if ($ds) {
        foreach ($ds as $d) {
            if ($date->format("Ymd") == $d->format("Ymd")) {
                $ret = true;
            }
        }
    }
    return $ret;
}
function churchservice_updateEventFromChurchCal($params, $source = null)
{
    $diff = null;
    // When $params["old_startdate"] is set, first the events are moved
    // to the diff of startdate-old_startdate
    if (isset($params["old_startdate"])) {
        $startdate = new DateTime($params["startdate"]);
        $old_startdate = new DateTime($params["old_startdate"]);
        $diff = $startdate->format("U") - $old_startdate->format("U");
        $db = db_query("select id, startdate from {cs_event} e where e.cc_cal_id=:cal_id", array(":cal_id" => $params["cal_id"]));
        foreach ($db as $e) {
            $sd = new DateTime($e->startdate);
            $sd->modify("+{$diff} seconds");
            db_update("cs_event")->fields(array("startdate" => $sd->format('Y-m-d H:i:s')))->condition('id', $e->id, "=")->execute();
        }
    }
    // When repeat_id is not given, this is only a time shift. So we can end the processing here.
    if (!isset($params["repeat_id"])) {
        return;
    }
    // Collect events in one array to collect the info which has to be created/deleted/updated
    $events = array();
    // Get all mapped events from DB
    $db = db_query("select id, startdate from {cs_event} e where e.cc_cal_id=:cal_id", array(":cal_id" => $params["cal_id"]));
    foreach ($db as $e) {
        $sd = new DateTime($e->startdate);
        $events[$sd->format('Y-m-d')] = array("status" => "delete", "id" => $e->id);
    }
    $o = _convertCTDateTimeToObjects($params);
    foreach (getAllDatesWithRepeats($o, -1000, +1000) as $d) {
        $sd = $d->format('Y-m-d');
        if (isset($events[$sd])) {
            // Event was already moved above through old_startdate
            $events[$sd]["status"] = "ok";
        } else {
            $events[$sd] = array("status" => "create");
        }
        $events[$sd]["startdate"] = $d->format('Y-m-d H:i:s');
    }
    $template = null;
    if (isset($params["eventTemplate"])) {
        $template = $params["eventTemplate"];
    }
    foreach ($events as $key => $do) {
        if ($do["status"] == "delete") {
            $params["id"] = $do["id"];
            $params["informDeleteEvent"] = 1;
            $params["deleteCalEntry"] = 0;
            churchservice_deleteEvent($params, $source);
        } else {
            if ($do["status"] == "create" && $template != null) {
                $params["id"] = null;
                $params["startdate"] = $do["startdate"];
                $params["eventTemplate"] = $template;
                churchservice_saveEvent($params, $source);
            }
        }
    }
}
/**
 * Get booking changes
 * 1. Check from originEvent if this is in newEvent
 * 2a. If not in newEvent, if it is in pastEvent, everything fine. Nothing changed
 * 2b. If is not in newEvent and in pastEvent, then it was deleted!
 * 3. If is in newEvent, then diff the changes
 * 4. Check if newEvent is not in originEvent, then there is something new
 * @param [type] $originEvent
 * @param [type] $newEvent
 */
function churchresource_getEventChangeImpact($newEvent, $pastEvent, $originEvent)
{
    $changes = array();
    $addCRChange = function (&$changes, $booking, $status, $startdate = null, $change = null) {
        $resource = churchcore_getTableData("cr_resource", null, "id = " . $booking["resource_id"]);
        $booking["resource"] = $resource[$booking["resource_id"]]->bezeichnung;
        $changes[] = array("booking" => $booking, "status" => $status, "startdate" => $startdate->format("Y-m-d"), "changes" => $change);
    };
    $splitDate = new DateTime($newEvent["startdate"]);
    // 1. Get all Dates for the origin Event
    if ($originEvent != null) {
        $ds = getAllDatesWithRepeats((object) $originEvent, 0, 9999, $splitDate);
        if ($ds) {
            foreach ($ds as $d) {
                if (!dateInCCEvent($d, $newEvent)) {
                    // 1. Date is not in newEvent
                    if (dateInCCEvent($d, $pastEvent)) {
                        // 2a. in past Event, everything fine. Nothing to check, because in past is no changes in bookings!
                        if (isset($originEvent["bookings"])) {
                            foreach ($originEvent["bookings"] as $booking) {
                                //$addCRChange($changes, $booking, "no.change", $d);
                            }
                        }
                    } else {
                        // 2b. Deleted! Now for each booking make change entry
                        if (isset($originEvent["bookings"])) {
                            foreach ($originEvent["bookings"] as $booking) {
                                $addCRChange($changes, $booking, "deleted", $d);
                            }
                        }
                    }
                } else {
                    // 3. event is in newEvent, now check bookings!
                    if (isset($originEvent["bookings"])) {
                        foreach ($originEvent["bookings"] as $booking) {
                            if (empty($newEvent["bookings"])) {
                                $addCRChange($changes, $booking, "deleted");
                            } else {
                                $newBooking = findBookingInNewEvent($booking, $newEvent);
                                if ($newBooking != null) {
                                    $change = makeBookingDiff($booking, $newBooking, getOneEventOutOfSeries($originEvent, $d), getOneEventOutOfSeries($newEvent, $d));
                                    if ($change != null) {
                                        $addCRChange($changes, $booking, "updated", $d, $change);
                                    }
                                    //else $addCRChange($changes, $booking, "no.changes", $d, $change);
                                }
                                // This is currently not supported, cause delete is not possible. Only set Status to deleted.
                                //else $addCRChange($changes, $booking, "error", $d, $change);
                            }
                        }
                    }
                    // Perhaps new resource in booking
                    if (isset($newEvent["bookings"])) {
                        foreach ($newEvent["bookings"] as $booking) {
                            $originBooking = findBookingInOriginEvent($booking, $originEvent);
                            if ($originBooking == null) {
                                $addCRChange($changes, $booking, "new", $d);
                            }
                        }
                    }
                }
            }
        }
    }
    // Now do 4.
    if (isset($newEvent["bookings"])) {
        $ds = getAllDatesWithRepeats((object) $newEvent, 0, 9999, $splitDate);
        if ($ds) {
            foreach ($ds as $d) {
                if (!dateInCCEvent($d, $originEvent)) {
                    if (isset($newEvent["bookings"])) {
                        foreach ($newEvent["bookings"] as $booking) {
                            $addCRChange($changes, $booking, "new", $d);
                        }
                    }
                }
            }
        }
    }
    return $changes;
}
/**
 * get current bookings
 * @return number|string
 */
function churchresource_getCurrentBookings()
{
    $txt = "";
    if (user_access("view", "churchresource")) {
        include_once "churchresource_db.php";
        // all bookings from now up tomorrow with status 2
        $res = getBookings(0, 1, "2");
        if ($res != null) {
            $arr = array();
            $counter = 0;
            foreach ($res as $r) {
                $r->startdate = new DateTime($r->startdate);
                $r->enddate = new DateTime($r->enddate);
                $ds = getAllDatesWithRepeats($r, 0, 1);
                if ($ds) {
                    foreach ($ds as $d) {
                        $counter++;
                        //TODO: not used
                        $arr[] = array("realstart" => new DateTime($d->format('Y-m-d H:i:s')), "startdate" => $r->startdate, "enddate" => $r->enddate, "person_name" => $r->person_name, "resource_id" => $r->resource_id, "repeat_id" => $r->repeat_id, "text" => $r->text, "id" => $r->id);
                    }
                }
            }
            if (count($arr)) {
                $resources = churchcore_getTableData("cr_resource");
                // custom sort function: cause there can be repeats in sorted the events
                function cmp($a, $b)
                {
                    if ($a["realstart"] == $b["realstart"]) {
                        return 0;
                    } else {
                        if ($a["realstart"] > $b["realstart"]) {
                            return 1;
                        } else {
                            -1;
                        }
                    }
                }
                usort($arr, "cmp");
                foreach ($arr as $val) {
                    $txt .= "<li><p><a href='?q=churchresource&id={$val['id']}'>{$val['text']}</a> ";
                    if ($val["repeat_id"] > 0) {
                        $txt .= '<img title="Serie startet vom ' . $val["startdate"]->format('d.m.Y H:i') . '" src="' . CHURCHRESOURCE . '/images/recurring.png" width="16px"/> ';
                    }
                    $txt .= "(" . $resources[$val["resource_id"]]->bezeichnung . ")<br/><small>" . $val["realstart"]->format('d.m.Y H:i') . " " . $val["person_name"] . "</small><br/>";
                }
                if ($txt) {
                    $txt = "<ul>{$txt}</ul>";
                }
            }
        }
    }
    return $txt;
}