Esempio n. 1
0
function simulate_main()
{
    if (isset($_SESSION["simulate"])) {
        $user = churchcore_getPersonById($_SESSION["simulate"]);
        $user->auth = getUserAuthorization($user->id);
        $_SESSION["user"] = $user;
        unset($_SESSION["simulate"]);
        if (isset($_SESSION["back"])) {
            header("Location: ?q=" . $_SESSION["back"]);
            unset($_SESSION["back"]);
        } else {
            header("Location: ?q=" . $_GET["link"]);
        }
    }
    if (isset($_GET["id"])) {
        $res = churchcore_getPersonById($_GET["id"]);
        if ($res != false) {
            _simulateUser($res);
            header("Location: ?q=" . $_GET["location"]);
            return "";
        }
    }
    $model = new CTForm("SimulateUserForm", "prooveEmail");
    $model->setHeader("Benutzer simulieren", t("simulate.information.text") . " " . t("please.enter.valid.email") . ":");
    $model->addField("email", "", "EMAIL", "EMail");
    $model->addButton("Simulieren", "ok");
    return $model->render();
}
Esempio n. 2
0
function login_main()
{
    global $q, $config;
    $txt = "";
    if (isset($config["admin_message"]) && $config["admin_message"] != "") {
        addErrorMessage($config["admin_message"]);
    }
    if (isset($_GET["message"]) && $_GET["message"] != "") {
        addInfoMessage($_GET["message"]);
    }
    // Sicherstellen, dass keiner eingelogt ist!
    if (!userLoggedIn()) {
        if (isset($config["login_message"])) {
            addInfoMessage($config["login_message"], true);
        }
        $model = new CTForm("LoginForm", "prooveLogin", "Login");
        $model->setHeader(t("login.headline"), t("please.fill.following.fields"));
        $model->addField("email", "", "INPUT_REQUIRED", t("email.or.username"), true);
        $model->addField("password", "", "PASSWORD", t("password"));
        if (!isset($config["show_remember_me"]) || $config["show_remember_me"] == 1) {
            $model->addField("rememberMe", "", "CHECKBOX", t("remember.me"));
        }
        $model->addButton(t("login"), "ok");
        if (isset($_GET["newpwd"])) {
            $res = db_query("select count(*) c from {cdb_person} where email='" . $_GET["email"] . "' and archiv_yn=0")->fetch();
            if ($_GET["email"] == "" || $res->c == 0) {
                $txt .= '<div class="alert alert-error"><p>Bitte ein g&uuml;ltige EMail-Adresse angeben, 
          an die das neue Passwort gesendet werden kann! 
          Diese Adresse muss im System schon eingerichtet sein.
          <p>Falls die E-Mail-Adresse schon eingerichtet sein sollte, 
          wende Dich bitte an <a href="' . variable_get("site_mail") . '">' . variable_get("site_mail") . '</a>.</div>';
            } else {
                $newpwd = random_string(8);
                $scrambled_password = scramble_password($newpwd);
                db_query("update {cdb_person} set password='******' where email='" . $_GET["email"] . "'");
                $content = "<h3>Hallo!</h3><p>Ein neues Passwort wurde f&uuml;r die E-Mail-Adresse <i>" . $_GET["email"] . "</i> angefordert: {$newpwd}";
                churchcore_systemmail($_GET["email"], "[" . variable_get('site_name') . "] Neues Passwort", $content, true, 1);
                churchcore_sendMails(1);
                $txt .= '<div class="alert alert-info">Hinweis: Ein neues Passwort wurde nun an <i>' . $_GET["email"] . '</i> gesendet.</div>';
                ct_log("Neues Passwort angefordert " . $_GET["email"], 2, "-1", "login");
            }
        } else {
            if (isset($_POST["email"]) && isset($_POST["password"]) && isset($_POST["directtool"])) {
                include_once CHURCHCORE . "/churchcore_db.php";
                $sql = "select * from {cdb_person} where email=:email and active_yn=1 and archiv_yn=0";
                $res = db_query($sql, array(":email" => $_POST["email"]))->fetch();
                if ($res == false) {
                    drupal_json_output(jsend()->fail("Unbekannte E-Mail-Adresse"));
                } else {
                    if (user_check_password($_POST["password"], $res)) {
                        login_user($res);
                        ct_log("Login durch Direct-Tool " . $_POST["directtool"] . " mit " . $_POST["email"], 2, "-1", "login");
                        drupal_json_output(jsend()->success());
                    } else {
                        drupal_json_output(jsend()->fail("Falsches Passwort"));
                    }
                }
                return;
            } else {
                if (isset($_GET["loginstr"]) && $_GET["loginstr"] != "" && isset($_GET["id"])) {
                    // L�sche alte cc_loginurrls die �lter sind als 14 tage
                    db_query("delete from {cc_loginstr} where DATEDIFF( current_date, create_date ) > 13");
                    $sql = "select * from {cc_loginstr} where loginstr=:loginstr and person_id=:id";
                    $res = db_query($sql, array(":loginstr" => $_GET["loginstr"], ":id" => $_GET["id"]))->fetch();
                    if ($res == false) {
                        $txt .= '<div class="alert alert-info">Fehler: Der verwendete Login-Link ist nicht mehr aktuell und kann deshalb nicht mehr verwendet werden. Bitte mit E-Mail-Adresse und Passwort anmelden!</div>';
                    } else {
                        // Nehme den LoginStr heraus, damit er nicht mi�braucht werden kann.
                        $sql = "delete from {cc_loginstr} where loginstr=:loginstr and person_id=:id";
                        $res = db_query($sql, array(":loginstr" => $_GET["loginstr"], ":id" => $_GET["id"]));
                        ct_log("Login User " . $_GET["id"] . " erfolgreich mit loginstr ", 2, "-1", "login");
                        $res = churchcore_getPersonById($_GET["id"]);
                        login_user($res);
                    }
                }
            }
        }
        $txt .= $model->render();
        $txt .= '<script>jQuery("#newpwd").click(function(k,a) {
         if (confirm("' . t('want.to.receive.new.password') . '")) {
           window.location.href="?newpwd=true&email="+jQuery("#LoginForm_email").val()+"&q=' . $q . '";
            }
          });</script>';
    } else {
        // Wenn man sich ummelden m�chte und zur Familie geh�rt (also gleiche E-Mail-Adresse)
        if (isset($_GET["family_id"])) {
            if (isset($_SESSION["family"][$_GET["family_id"]])) {
                //logout_current_user();
                login_user($_SESSION["family"][$_GET["family_id"]]);
                $txt .= '<div class="alert alert-info">Ummelden erfolgreich! Du arbeitest nun mit der Berechtigung von ' . $_SESSION["user"]->vorname . ' ' . $_SESSION["user"]->name . '.</div>';
            } else {
                $txt .= '<div class="alert alert-info">Ummelden zu Id:' . $_GET["family_id"] . ' hat nicht funktioniert, Session ist leer!</div>';
            }
        } else {
            $txt .= '<div class="alert alert-info"><i>Hinweis:</i> Du bist angemeldet als ' . $_SESSION["user"]->vorname . ', weiter geht es <a href="?q=home">hier</a>!</div>';
        }
    }
    return $txt;
}
Esempio n. 3
0
/**
 * info for pending requests
 * TODO: rename churchservice_openservice_rememberdays, f.e. to sendOpenServiceRememberMail
 * TODO: could sql queries be reduced?
 */
function churchservice_openservice_rememberdays()
{
    global $base_url;
    include_once "churchservice_db.php";
    $delay = (int) getConf('churchservice_openservice_rememberdays');
    $dt = new datetime();
    // get ONE eventService needed to send (not yet send or still pending).
    // from persons having an email ??und auch gemappt wurde??.
    //   $sql = "SELECT es.id, p.id p_id, p.vorname, p.email, es.modified_pid,
    //             IF (password IS NULL AND loginstr IS NULL AND lastlogin IS NULL,1,0) AS invite
    //           FROM {cs_eventservice} es, {cs_event} e, {cc_cal} cal, {cs_service} s, {cdb_person} p
    //           WHERE e.valid_yn=1 AND e.cc_cal_id=cal.id AND es.valid_yn=1 AND es.zugesagt_yn=0
    //             AND es.cdb_person_id IS NOT NULL AND es.service_id=s.id AND s.sendremindermails_yn=1
    //             AND es.event_id=e.id AND e.Startdate>=current_date
    //             AND ((es.mailsenddate IS NULL) OR (DATEDIFF(current_date,es.mailsenddate)>=$delay))
    //             AND p.email!='' AND p.id=es.cdb_person_id LIMIT 1";
    $sql = "SELECT es.id, p.id p_id, p.vorname, p.spitzname, p.name, p.email, es.modified_pid,\n            IF (password IS NULL AND loginstr IS NULL AND lastlogin IS NULL,1,0) AS invite\n          FROM {cs_eventservice} es, {cs_event} e, {cc_cal} cal, {cs_service} s, {cdb_person} p\n          WHERE e.valid_yn=1 AND e.cc_cal_id=cal.id AND es.valid_yn=1 AND es.zugesagt_yn=0\n            AND es.cdb_person_id IS NOT NULL AND es.service_id=s.id AND s.sendremindermails_yn=1\n            AND es.event_id=e.id AND e.Startdate>=current_date\n            AND ((es.mailsenddate IS NULL) OR (DATEDIFF(current_date,es.mailsenddate)>={$delay}))\n            AND p.email!='' AND p.id=es.cdb_person_id\n          GROUP BY p_id";
    //group to get each person only once, so querying all together dont interfere with the other services of the same person
    $usersToMail = db_query($sql);
    $i = 0;
    // process only 15 services to prevent too many mails at once
    while ($i++ < 15 && ($u = $usersToMail->fetch())) {
        $data = array('inviter' => churchcore_getPersonById($u->modified_pid), 'url' => "{$base_url}?q=home&id={$u->p_id}&loginstr=" . churchcore_createOnTimeLoginKey($u->p_id), 'requestedServices' => array(), 'approvedServices' => array(), 'user' => $u, 'nickname' => $u->spitzname ? $u->spitzname : $u->vorname);
        // Person was not yet invited -> send invitation.
        if ($u->invite == 1) {
            include_once CHURCHDB . '/churchdb_ajax.php';
            churchdb_invitePersonToSystem($u->p_id);
        }
        $servicesOfPerson = db_query("\n       SELECT es.id AS id, es.zugesagt_yn AS approved, cal.bezeichnung AS event, DATE_FORMAT(e.startdate, '%d.%m.%Y %H:%i') AS datum,\n         e.id AS event_id, s.bezeichnung AS service, sg.bezeichnung AS servicegroup, es.mailsenddate\n       FROM {cs_eventservice} es, {cs_event} e, {cc_cal} cal, {cs_service} s, {cs_servicegroup} sg\n       WHERE e.valid_yn=1 AND cal.id=e.cc_cal_id AND es.valid_yn=1 AND es.cdb_person_id=:p_id\n        AND s.sendremindermails_yn=1 AND es.event_id=e.id AND es.service_id=s.id AND sg.id=s.servicegroup_id\n        AND e.startdate>=current_date\n       ORDER BY e.startdate", array(":p_id" => $u->p_id));
        foreach ($servicesOfPerson as $s) {
            if ($s->approved == 1) {
                $data['approvedServices'][] = $s;
            } else {
                $data['requestedServices'][] = $s;
            }
            db_update("cs_eventservice")->fields(array("mailsenddate" => $dt->format('Y-m-d H:i:s')))->condition('id', $s->id, "=")->execute();
        }
        $lang = getUserLanguage($u->p_id);
        $content = getTemplateContent('email/openServiceReminder', 'churchservice', $data, null, $lang);
        churchservice_send_mail("[" . getConf('site_name') . "] " . t2($lang, 'there.are.pending.services'), $content, $u->email);
        $usersToMail->next();
    }
}
Esempio n. 4
0
/**
 * main function for login
 * @return string
 */
function login_main()
{
    global $q, $config, $user;
    $txt = "";
    if ($t = getConf("admin_message")) {
        addErrorMessage($t);
    }
    if ($t = getVar("message")) {
        addInfoMessage($t);
    }
    // Sicherstellen, dass keiner eingelogt ist!
    if (!userLoggedIn()) {
        if ($t = getVar("login_message")) {
            addInfoMessage($t, true);
        }
        $form = new CTForm("LoginForm", "validateLogin", "Login");
        $form->setHeader(t("login.headline"), t("please.fill.following.fields"));
        $form->addField("email", "", "INPUT_REQUIRED", t("email.or.username"), true);
        if (getVar("email")) {
            $form->fields["email"]->setValue(getVar("email"));
        }
        $form->addField("password", "", "PASSWORD", t("password"));
        // TODO: when is this false?
        if (getConf("show_remember_me", 1) == 1) {
            $form->addField("rememberMe", "", "CHECKBOX", t("remember.me"));
        }
        $form->addButton(t("login"), "ok");
        // access through externale tools through GET and additional direct
        // POST so no GET is used , so it is not visible in the URL
        if (getVar("email", false, $_POST) && getVar("password", false, $_POST) && getVar("directtool", false, $_POST)) {
            include_once CHURCHCORE . "/churchcore_db.php";
            $email = getVar("email", false, $_POST);
            $password = getVar("password", false, $_POST);
            $directTool = getVar("directtool", false, $_POST);
            $res = db_query("SELECT * FROM {cdb_person}\n                       WHERE email=:email AND active_yn=1 AND archiv_yn=0", array(":email" => $email))->fetch();
            if (!$res) {
                drupal_json_output(jsend()->fail(t('email.unknown')));
            } else {
                if (user_check_password($password, $res)) {
                    login_user($res, null, false);
                    ct_log("Login by Direct-Tool {$directTool} with {$email}", 2, "-1", "login");
                    drupal_json_output(jsend()->success());
                } else {
                    drupal_json_output(jsend()->fail(t('wrong.password')));
                }
            }
            return;
        } else {
            if (($loginstr = getVar("loginstr")) && ($id = getVar('id'))) {
                // delete login strings older then 14 days
                db_query("DELETE FROM {cc_loginstr}\n                WHERE DATEDIFF( current_date, create_date ) > 13");
                $res = db_query("SELECT * FROM {cc_loginstr}\n                       WHERE loginstr=:loginstr AND person_id=:id", array(":loginstr" => $loginstr, ":id" => $id))->fetch();
                if (!$res) {
                    $txt .= '<div class="alert alert-info">' . t('login.string.too.old') . '</div>';
                } else {
                    // delete current loginKey to prevent misuse
                    $res = db_query("DELETE FROM {cc_loginstr}\n                         WHERE loginstr=:loginstr AND person_id=:id", array(":loginstr" => $loginstr, ":id" => $id));
                    ct_log("Login User {$id} erfolgreich mit loginstr ", 2, "-1", "login");
                    $res = churchcore_getPersonById($id);
                    login_user($res);
                }
            }
        }
        $txt .= $form->render();
        $txt .= '<script>jQuery("#newpwd").click(function(k,a) {
         if (confirm("' . t('want.to.receive.new.password') . '")) {
           window.location.href="?q=login/newpwd&email="+jQuery("#LoginForm_email").val();
            }
          });</script>';
    } else {
        // switch to another family user (same email)
        if ($familyId = getVar("family_id")) {
            if (isset($_SESSION["family"][$familyId])) {
                // logout_current_user();
                login_user($_SESSION["family"][$familyId]);
                $txt .= '<div class="alert alert-info">' . t('user.succesfully.changed.now.you.work.with.permissions.of.x', $_SESSION["user"]->vorname . ' ' . $_SESSION["user"]->name) . '</div>';
            } else {
                $txt .= "<div class='alert alert-info'>" . t('user.change.to.familyX.failed.session.is.empty', $familyId) . "</div>";
            }
        } else {
            if (getVar("directtool", false, $_POST)) {
                drupal_json_output(jsend()->success("Already logged in"));
            } else {
                $txt .= '<div class="alert alert-info">' . t('you.are.logged.in.as.x.click.y.to.continue', $_SESSION["user"]->vorname, '<a href="?q=home">' . t('home') . '</a>') . '</div>';
            }
        }
    }
    return $txt;
}
/**
 * update event service
 * 
 * @param array $params
 * @throws CTNoPermission
 * @return array
 */
function churchservice_updateEventService($params)
{
    global $user, $base_url;
    $id = $params["id"];
    $name = isset($params["name"]) ? $params["name"] : null;
    $cdb_person_id = isset($params["cdb_person_id"]) ? $params["cdb_person_id"] : null;
    $reason = isset($params["reason"]) ? $params["reason"] : null;
    $zugesagt_yn = $params["zugesagt_yn"];
    include_once CHURCHSERVICE . "/churchservice_db.php";
    $res = array();
    if ($name == "null") {
        $name = null;
    }
    if ($cdb_person_id == "null") {
        $cdb_person_id = null;
    }
    // look if event is still valid
    $arr = db_query("SELECT * FROM {cs_eventservice} WHERE id=:id", array(":id" => $id))->fetch();
    if (!$arr) {
        return "Entry not found, id not valid!";
    }
    if ($arr->valid_yn != 1 && !isset($params["valid_yn"])) {
        return "Eintrag konnte nicht angepasst werden, da veraltet. Bitte neu laden!";
    }
    // check auth
    $auth = churchservice_getAuthorization();
    // Es ist trotzdem erlaubt, wenn die PersonId eingetragen ist, dann wurde er ja angefragt
    if (!isset($auth["editservice"][$arr->service_id]) && !isset($auth["memberservice"][$arr->service_id]) && !churchService_adminOfEvent($arr->event_id) && $arr->cdb_person_id != $user->id) {
        throw new CTNoPermission("editservice", "churchservice");
    }
    // Wenn die neue �nderung vom gleichen User kommt und noch kein Cron gelaufen ist,
    // Oder wenn valid_yn valide ist, denn dann soll es upgedates werden!
    // brauchen wir kein neuen Insert, sondern machen nur ein Update.
    // Denn wahrscheinlich war es vorher nur ein Versehen.
    // TODO: translation correct?
    // if changing user is the same as last time and cron had not yet run
    // or if valid_yn is valide (update wished), we dont need an insert, only an update,
    // because the last edit probably was a mistake
    $dt = new datetime();
    if ($arr->modified_pid == $user->id && $arr->mailsenddate == null || isset($params["valid_yn"])) {
        $valid_yn = 1;
        if (isset($params["valid_yn"])) {
            $valid_yn = $params["valid_yn"];
        }
        db_update("cs_eventservice")->fields(array("name" => $name, "cdb_person_id" => $cdb_person_id, "valid_yn" => $valid_yn, "zugesagt_yn" => $zugesagt_yn, "reason" => $reason, "mailsenddate" => null, "modified_date" => $dt->format('Y-m-d H:i:s'), "modified_pid" => $user->id))->condition("id", $id, "=")->execute();
        $new_id = $id;
    } else {
        // new entry for edit
        $new_id = db_insert("cs_eventservice")->fields(array("event_id" => $arr->event_id, "service_id" => $arr->service_id, "valid_yn" => 1, "counter" => $arr->counter, "name" => $name, "cdb_person_id" => $cdb_person_id, "zugesagt_yn" => $zugesagt_yn, "reason" => $reason, "modified_date" => $dt->format('Y-m-d H:i:s'), "modified_pid" => $user->id))->execute();
        //if all ok set existing entry to old
        db_update("cs_eventservice")->fields(array("valid_yn" => 0))->condition("id", $id, "=")->execute();
    }
    include_once CHURCHCORE . "/churchcore_db.php";
    $leader = churchcore_getPersonById($arr->modified_pid);
    $event = db_query("SELECT e.startdate datum, c.bezeichnung FROM {cs_event} e, {cc_cal} c\n                     WHERE e.cc_cal_id=c.id and e.id=:event_id", array(":event_id" => $arr->event_id))->fetch();
    $service = churchcore_getTableData("cs_service", "", "id=" . $arr->service_id);
    if ($event && $service) {
        $service = $service[$arr->service_id];
        $subject = "[" . readConf('site_name', "ChurchTools") . "] ";
        $txt = "";
        // confirm
        if ($zugesagt_yn == 1) {
            $txt .= t("surname.name.has.approved.name.for.service.x.for.date.event", $user->vorname, $user->name, $service->bezeichnung, $event->datum, $event->bezeichnung, $name);
            $subject .= t("surname.name.has.approved.a.request", $user->vorname, $user->name);
        } else {
            if ($name) {
                $txt .= t("surname.name.has.proposed.name.for.service.x.for.date.event", $user->vorname, $user->name, $service->bezeichnung, $event->datum, $event->bezeichnung, $name);
                $subject .= t("surname.name.has.proposed.someone", $user->vorname, $user->name);
            } else {
                $txt .= t("surname.name.has.canceled.the.service.x.for.date.event", $user->vorname, $user->name, $service->bezeichnung, $event->datum, $event->bezeichnung);
                $subject .= t("surname.name.has.canceled.a.request", $user->vorname, $user->name);
            }
        }
        if ($reason != null) {
            $txt .= "<p>Folgendes wurde als Grund angegeben: " . $reason;
        }
        ct_notify("service", $arr->service_id, $txt);
        if ($leader != null) {
            // send mail, if someone other then the inquirer himself confirmed or canceled
            //TODO: maybe use asker, better to understand for nonenglish programmers
            //TODO: use email template
            if (!empty($leader->email) && $user != null && $leader->id != $user->id) {
                $setting = churchcore_getUserSettings("churchservice", $leader->id);
                if (isset($setting["informInquirer"]) && $setting["informInquirer"] == 1) {
                    $txt = "<h3>Hallo " . $leader->vorname . ",</h3><p>\n                 " . $txt;
                    $txt .= '<p><a href="' . $base_url . '?q=churchservice&id=' . $arr->event_id . '" class="btn btn-primary">Event aufrufen</a>';
                    churchservice_send_mail($subject, $txt, $leader->email);
                }
            }
            if (!isset($setting["informInquirer"])) {
                churchcore_saveUserSetting("churchservice", $leader->id, "informInquirer", 0);
            }
        }
    }
    $arr = db_query("SELECT es.*, concat(p.vorname,' ',p.name) as modifieduser FROM {cs_eventservice} es, {cdb_person} p \n                    WHERE p.id=es.modified_pid and es.id=:id", array(":id" => $new_id))->fetch();
    $res["eventservice"] = churchservice_extractEventServiceData($arr);
    $res["result"] = true;
    return $res;
}
/**
 * TODO: too much code in churchresource_updateBooking, split it up
 * FIXME: the changes for using email template are breaking logging in case no email is send
 * otherwise logging of complete mails dont seems useful => only log important things in a short text?
 *
 * @param array $params
 * @return multitype:multitype:unknown
 */
function churchresource_updateBooking($params, $sendEMails = true)
{
    global $base_url, $user;
    $oldBooking = getBooking($params["id"]);
    $bUser = churchcore_getPersonById($oldBooking->person_id);
    $ressources = churchcore_getTableData("cr_resource", "resourcetype_id,sortkey,bezeichnung");
    $i = new CTInterface();
    $i->setParam("resource_id");
    $i->setParam("status_id");
    $i->addTypicalDateFields();
    $i->setParam("text", false);
    $i->setParam("location", false);
    $i->setParam("note", false);
    if (empty($params["text"])) {
        $res = db_query('SELECT text FROM {cr_booking}
                     WHERE id=:id', array(":id" => $params["id"]))->fetch();
        $params["text"] = $res->text;
    }
    $i->setParam("person_id", false);
    $id = db_update("cr_booking")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
    $changes = null;
    $exceptions = churchcore_getTableData("cr_exception", null, "booking_id=" . $params["id"]);
    // look which exceptions are already saved in DB.
    if (isset($params["exceptions"])) {
        foreach ($params["exceptions"] as $exception) {
            $current_exc = null;
            // It is not possible to search exceptions by id, because ChurchCal Exc have other IDs
            if ($exceptions) {
                foreach ($exceptions as $e) {
                    if (churchcore_isSameDay($e->except_date_start, $exception["except_date_start"]) && churchcore_isSameDay($e->except_date_end, $exception["except_date_end"])) {
                        $current_exc = $e;
                    }
                }
            }
            if ($current_exc) {
                $exceptions[$current_exc->id]->exists = true;
            } else {
                $changes["add_exception"][] = $exception;
            }
        }
    }
    // delete removed exceptions from DB.
    if ($exceptions) {
        foreach ($exceptions as $e) {
            if (!isset($e->exists)) {
                $changes["del_exception"][] = (array) $e;
            }
        }
    }
    // get all additions
    $additions = churchcore_getTableData("cr_addition", null, "booking_id=" . $params["id"]);
    // look which additions are already saved in DB.
    if (isset($params["additions"])) {
        foreach ($params["additions"] as $addition) {
            $current_add = null;
            // It is not possible to search additions by id, because ChurchCal adds have other IDs
            if ($additions) {
                foreach ($additions as $a) {
                    if (churchcore_isSameDay($a->add_date, $addition["add_date"]) && $a->with_repeat_yn == $addition["with_repeat_yn"]) {
                        $current_add = $a;
                    }
                }
            }
            if ($current_add) {
                $additions[$current_add->id]->exists = true;
            } else {
                $changes["add_addition"][] = $addition;
            }
        }
    }
    // delete removed additions from DB.
    if ($additions) {
        foreach ($additions as $a) {
            // churchresource_delAddition($a->id);
            if (!isset($a->exists)) {
                $changes["del_addition"][] = (array) $a;
            }
        }
    }
    // save new exceptions
    $res_exceptions = array();
    $res_additions = array();
    $days = array();
    $resources = churchcore_getTableData("cr_resource");
    //TODO: only get needed resource_id
    if ($changes) {
        if (isset($changes["add_exception"])) {
            foreach ($changes["add_exception"] as $exc) {
                // Check, if exception not alreay in DB (only possible when coming from Cal)
                $db = db_query("SELECT id FROM {cr_exception}\n                        WHERE booking_id=:booking_id AND except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if (!$db) {
                    $id = addException($params["id"], $exc["except_date_start"], $exc["except_date_end"], $user->id);
                    if (isset($exc["id"])) {
                        $res_exceptions[$exc["id"]] = $id;
                    }
                    $days[] = $exc["except_date_start"];
                }
            }
            if ($sendEMails && getConf("churchresource_send_emails", true) && count($days) && $bUser) {
                $data = array('canceled' => true, 'surname' => $bUser->vorname, 'name' => $bUser->name, 'nickname' => $bUser->spitzname ? $bUser->spitzname : $bUser->vorname, 'user' => $user, 'resource' => $resources[$params["resource_id"]]->bezeichnung, 'booking' => $booking, 'days' => implode(", ", $days), 'person' => $bUser, 'contact' => getConf('site_mail'));
                $lang = getUserLanguage($oldBooking->person_id);
                $content = getTemplateContent('email/bookingRequest', 'churchresource', $data, null, $lang);
                churchresource_send_mail("[" . getConf('site_name') . "] " . t2($lang, 'updated.booking.request') . ": " . $params["text"], $content, $bUser->email);
            }
        }
        if (isset($changes["del_exception"])) {
            foreach ($changes["del_exception"] as $exc) {
                $db = db_query("SELECT id FROM {cr_exception}\n                        WHERE booking_id=:booking_id AND except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if ($db) {
                    churchresource_delException(array("id" => $db->id));
                }
            }
        }
        if (isset($changes["add_addition"])) {
            foreach ($changes["add_addition"] as $add) {
                $db = db_query("SELECT id FROM {cr_addition}\n                      WHERE booking_id=:booking_id AND add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if (!$db) {
                    $id = addAddition($params["id"], $add["add_date"], $add["with_repeat_yn"], $user->id);
                    if (isset($add["id"])) {
                        $res_additions[$add["id"]] = $id;
                    }
                }
            }
        }
        if (isset($changes["del_addition"])) {
            foreach ($changes["del_addition"] as $add) {
                $db = db_query("SELECT id FROM {cr_addition}\n                      WHERE booking_id=:booking_id AND add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if ($db != false) {
                    churchresource_delAddition($db->id);
                }
            }
        }
    }
    // FIXME: check logic for correct function; i am not sure what should happen exactly in which cases
    // TODO: maybe use $params as data and add further values
    $booking = getBooking($params["id"]);
    $changedFields = churchcore_getFieldChanges(getBookingFields(), $oldBooking, $booking, false);
    $data = array('enddate' => churchcore_stringToDateDe($params["enddate"]), 'startdate' => churchcore_stringToDateDe($params["startdate"]), 'resource' => $resources[$params["resource_id"]]->bezeichnung, 'changes' => str_replace("\n", "<br>", $changedFields), 'booking' => $booking, 'bookingUrl' => $base_url . "?q=churchresource&id=" . $params["id"], 'text' => $params['text'], 'note' => isset($params['location']) ? $params['location'] : "", 'pending' => $params["status_id"] == CR_PENDING, 'approved' => $params["status_id"] == CR_APPROVED && ($oldBooking->status_id != CR_APPROVED || $changedFields != null), 'canceled' => $params["status_id"] == CR_CANCELED, 'deleted' => $params["status_id"] == CR_DELETED, 'contact' => getConf('site_mail'));
    $logInfo = ' :: ' . t('bookingX.for.resource.on.datetime', $params["text"], $resources[$params["resource_id"]]->bezeichnung, $params["startdate"], isset($params['location']) ? $params['location'] : "");
    $subject = t('booking.request.updated');
    if ($data['pending']) {
        $logInfo = t('booking.updated') . $logInfo;
    } elseif ($data['approved']) {
        $logInfo = t('booking.approved') . $logInfo;
    } elseif ($data['canceled']) {
        $logInfo = t('booking.canceled') . $logInfo;
    } elseif ($data['deleted']) {
        $logInfo = t('booking.deleted') . $logInfo;
    }
    if ($sendEMails && getConf("churchresource_send_emails", true)) {
        if (($params["status_id"] != $oldBooking->status_id || $changedFields != null) && $bUser) {
            $adminmails = explode(",", $resources[$params["resource_id"]]->admin_person_ids);
            // if current user is not resource admin OR is not the booking creating user
            if (!in_array($user->id, $adminmails) || $user->id != $bUser->id) {
                $content = getTemplateContent('email/bookingUpdated', 'churchresource', $data);
                churchresource_send_mail("[" . getConf('site_name') . "] {$subject}: " . $params["text"], $content, $bUser->email);
            }
        }
    }
    if ($changedFields) {
        cr_log("UPDATE BOOKING\n" . $logInfo, 3, $booking->id);
    }
    return array("exceptions" => $res_exceptions, "additions" => $res_additions);
}
/**
 * Infos f�r noch zu best�tigende Dienste
 */
function churchservice_openservice_rememberdays()
{
    global $base_url;
    include_once "churchservice_db.php";
    $delay = readConf('churchservice_openservice_rememberdays');
    $dt = new datetime();
    // Checken, ob EIN EventService noch nicht gesendet wurde, bzw. schon so alt ist.
    // Pr�fe dabei, ob die Person eine EMail-Adresse hat und auch gemappt wurde.
    $sql = "SELECT es.id, p.id p_id, p.vorname, p.email, es.modified_pid, if (password is null and loginstr is null and lastlogin is null,1,0) as invite  \n                    FROM {cs_eventservice} es, {cs_event} e, {cc_cal} cal, {cs_service} s, {cdb_person} p \n                    where e.valid_yn=1 and e.cc_cal_id=cal.id and es.valid_yn=1 and es.zugesagt_yn=0 and es.cdb_person_id is not null\n                      and es.service_id=s.id and s.sendremindermails_yn=1 \n                      and es.event_id=e.id and e.Startdate>=current_date\n                      and ((es.mailsenddate is null) or (datediff(current_date,es.mailsenddate)>={$delay}))\n                      and p.email!='' and p.id=es.cdb_person_id limit 1";
    $res = db_query($sql)->fetch();
    $sql2 = "SELECT es.id id, cal.bezeichnung event, DATE_FORMAT(e.startdate, '%d.%m.%Y %H:%i') datum, e.id event_id,\n                 s.bezeichnung service, sg.bezeichnung servicegroup, es.mailsenddate\n              FROM {cs_eventservice} es, {cs_event} e, {cc_cal} cal, {cs_service} s, {cs_servicegroup} sg \n                 where e.valid_yn=1 and cal.id=e.cc_cal_id and es.valid_yn=1 and es.zugesagt_yn=:zugesagt and es.cdb_person_id=:p_id\n                  and s.sendremindermails_yn=1 \n                  and es.event_id=e.id and es.service_id=s.id and sg.id=s.servicegroup_id\n                  and e.startdate>=current_date\n                  order by e.startdate";
    $i = 0;
    // Lasse 15 EventServices durch, dann warten bis n�chste Cron, sonst werden es zu viele Mails
    while ($res && $i < 15) {
        // Wenn einer vorhanden ist, dann suche nach weiteren offenen Diensten f�r die Person
        $txt = "<h3>Hallo " . $res->vorname . ",</h3><p>";
        $inviter = churchcore_getPersonById($res->modified_pid);
        $txt .= "Du wurdest in dem Dienstplan auf " . readConf('site_name', 'ChurchTools');
        if ($inviter != null) {
            $txt .= ' von <i>' . $inviter->vorname . " " . $inviter->name . "</i>";
        }
        $txt .= " zu Diensten vorgeschlagen. <br/>Zum Zu- oder Absagen bitte hier klicken:";
        $loginstr = churchcore_createOnTimeLoginKey($res->p_id);
        $txt .= '<p><a href="' . $base_url . '?q=home&id=' . $res->p_id . '&loginstr=' . $loginstr . '" class="btn btn-primary">%sitename</a>';
        $txt .= "<p><p><b>Folgende Dienst-Termine sind von Dir noch nicht bearbeitet:</b><ul>";
        $arr = db_query($sql2, array(":p_id" => $res->p_id, ":zugesagt" => 0));
        foreach ($arr as $res2) {
            $txt .= "<li> " . $res2->datum . " " . $res2->event . ":  " . $res2->service . " (" . $res2->servicegroup . ")";
            db_update("cs_eventservice")->fields(array("mailsenddate" => $dt->format('Y-m-d H:i:s')))->condition('id', $res2->id, "=")->execute();
        }
        $txt .= '</ul>';
        $arr = db_query($sql2, array(":p_id" => $res->p_id, ":zugesagt" => 1));
        $txt2 = "";
        foreach ($arr as $res2) {
            $txt2 .= "<li> " . $res2->datum . " - " . $res2->event . ":  " . $res2->service . " (" . $res2->servicegroup . ")";
            if ($res2->mailsenddate == null) {
                $txt2 .= " NEU!";
            }
            db_update("cs_eventservice")->fields(array("mailsenddate" => $dt->format('Y-m-d H:i:s')))->condition('id', $res2->id, "=")->execute();
        }
        if ($txt2 != "") {
            $txt .= "<p><p><b>Bei folgenden Diensten hast Du schon zugesagt:</b><ul>" . $txt2;
            $txt .= "</ul>";
        }
        // Person wurde noch nicht eingeladen, also schicke gleich eine Einladung mit!
        if ($res->invite == 1) {
            include_once CHURCHDB . '/churchdb_ajax.php';
            churchdb_invitePersonToSystem($res->p_id);
            $txt .= "<p><b>Da Du noch nicht kein Zugriff auf das System hast, bekommst Du noch eine separate E-Mail, mit der Du Dich dann anmelden kannst!.</b>";
        }
        churchservice_send_mail("[" . readConf('site_name', 'ChurchTools') . "] Es sind noch Dienste offen", $txt, $res->email);
        $i = $i + 1;
        $res = db_query($sql)->fetch();
    }
}
function churchresource_updateBooking($params, $changes = null)
{
    global $base_url, $user;
    // Only bigchange, when I get repeat_id. Otherwise it is only a time shift.
    $bigchange = isset($params["repeat_id"]);
    $old_arr = getBooking($params["id"]);
    $buser = churchcore_getPersonById($old_arr->person_id);
    $ressources = churchcore_getTableData("cr_resource", "resourcetype_id,sortkey,bezeichnung");
    $i = new CTInterface();
    $i->setParam("resource_id");
    $i->setParam("status_id");
    if ($bigchange) {
        $i->addTypicalDateFields();
        $i->setParam("text");
        $i->setParam("location");
        $i->setParam("note");
    } else {
        $i->setParam("startdate");
        $i->setParam("enddate");
        $res = db_query('select * from {cr_booking} where id=:id', array(":id" => $params["id"]))->fetch();
        $params["text"] = $res->text;
    }
    $i->setParam("person_id");
    $id = db_update("cr_booking")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
    // No changes mean not from Cal, so I have to check changes manuelly
    if (is_null($changes) && $bigchange) {
        // Hole alle Exceptions aus der DB
        $exc = churchcore_getTableData("cr_exception", null, "booking_id=" . $params["id"]);
        // Vergleiche erst mal welche schon in der DB sind oder noch nicht in der DB sind.
        if (isset($params["exceptions"])) {
            foreach ($params["exceptions"] as $exception) {
                $current_exc = null;
                // Look for Exc. This is not possible to make by id, cause ChurchCal Exc have other IDs
                if ($exc != false) {
                    foreach ($exc as $e) {
                        if (churchcore_isSameDay($e->except_date_start, $exception["except_date_start"]) && churchcore_isSameDay($e->except_date_end, $exception["except_date_end"])) {
                            $current_exc = $e;
                        }
                    }
                }
                if ($current_exc != null) {
                    $exc[$current_exc->id]->vorhanden = true;
                } else {
                    $changes["add_exception"][] = $exception;
                }
            }
        }
        // L�sche nun alle, die in der DB sind, aber nicht mehr vorhanden sind.
        if ($exc != false) {
            foreach ($exc as $e) {
                if (!isset($e->vorhanden)) {
                    $changes["del_exception"][] = (array) $e;
                }
            }
        }
        // Hole alle Additions aus der DB
        $add = churchcore_getTableData("cr_addition", null, "booking_id=" . $params["id"]);
        // Vergleiche erst mal welche schon in der DB sind oder noch nicht in der DB sind.
        if (isset($params["additions"])) {
            foreach ($params["additions"] as $addition) {
                $current_add = null;
                // Look for additions. This is not possible to make by id, cause ChurchCal Additions have other IDs
                if ($add != false) {
                    foreach ($add as $a) {
                        if (churchcore_isSameDay($a->add_date, $addition["add_date"]) && $a->with_repeat_yn == $addition["with_repeat_yn"]) {
                            $current_add = $a;
                        }
                    }
                }
                if ($current_add != null) {
                    $add[$current_add->id]->vorhanden = true;
                } else {
                    $changes["add_addition"][] = $addition;
                }
            }
        }
        // L�sche nun alle, die in der DB sind, aber nicht mehr vorhanden sind.
        if ($add != false) {
            foreach ($add as $a) {
                if (!isset($a->vorhanden)) {
                    //churchresource_delAddition($a->id);
                    $changes["del_addition"][] = (array) $a;
                }
            }
        }
    }
    // New Exception-Ids will be saved here
    $res_exceptions = array();
    $res_additions = array();
    $days = array();
    // Now do the changes!
    if ($changes != null) {
        if (isset($changes["add_exception"])) {
            foreach ($changes["add_exception"] as $exc) {
                // Check, if exception not alreay in DB (only when coming from Cal it is possible)
                $db = db_query("select id from {cr_exception} where booking_id=:booking_id and except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if ($db == false) {
                    $id = addException($params["id"], $exc["except_date_start"], $exc["except_date_end"], $user->id);
                    if (isset($exc["id"])) {
                        $res_exceptions[$exc["id"]] = $id;
                    }
                    $days[] = $exc["except_date_start"];
                }
            }
            if (count($days) > 0 && $buser != null) {
                $txt = "<h3>Hallo " . $buser->vorname . "!</h3><p>Bei Deiner Serien-Buchungsanfrage '" . $params["text"] . "' fuer " . $ressources[$params["resource_id"]]->bezeichnung . " mussten leider von " . $user->vorname . " " . $user->name . " folgende Tage abgelehnt werden: <b>" . implode(", ", $days) . "</b><p>";
                churchresource_send_mail("[" . variable_get('site_name') . "] Aktualisierung der Buchungsanfrage: " . $params["text"], $txt, $buser->email);
            }
        }
        if (isset($changes["del_exception"])) {
            foreach ($changes["del_exception"] as $exc) {
                $db = db_query("select id from {cr_exception} where booking_id=:booking_id and except_date_start=:start", array(":booking_id" => $params["id"], ":start" => $exc["except_date_start"]))->fetch();
                if ($db != false) {
                    churchresource_delException(array("id" => $db->id));
                }
            }
        }
        if (isset($changes["add_addition"])) {
            foreach ($changes["add_addition"] as $add) {
                $db = db_query("select id from {cr_addition} where booking_id=:booking_id and add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if ($db == false) {
                    $id = addAddition($params["id"], $add["add_date"], $add["with_repeat_yn"], $user->id);
                    if (isset($add["id"])) {
                        $res_additions[$add["id"]] = $id;
                    }
                }
            }
        }
        if (isset($changes["del_addition"])) {
            foreach ($changes["del_addition"] as $add) {
                $db = db_query("select id from {cr_addition} where booking_id=:booking_id and add_date=:date", array(":booking_id" => $params["id"], ":date" => $add["add_date"]))->fetch();
                if ($db != false) {
                    churchresource_delAddition($db->id);
                }
            }
        }
    }
    $txt = "";
    $info = "'" . $params["text"] . "' fuer " . $ressources[$params["resource_id"]]->bezeichnung . " (" . $params["startdate"] . "h";
    if ($params["location"] != "") {
        $info = $info . " in " . $params["location"];
    }
    $info = $info . ")";
    $arr = getBooking($params["id"]);
    $changes = churchcore_getFieldChanges(getBookingFields(), $old_arr, $arr, false);
    if ($params["status_id"] == 1) {
        $txt = " wurde aktualisiert und wartet auf Genehmigung.";
    } else {
        if ($params["status_id"] == 2 && ($old_arr->status_id != 2 || $changes != null)) {
            $txt = " wurde von {$user->vorname} {$user->name} genehmigt!<p>";
        } else {
            if ($params["status_id"] == 3) {
                $txt = " wurde leider abgelehnt, bitte suche Dir einen anderen Termin.<p>";
            } else {
                if ($params["status_id"] == 99) {
                    $txt = " wurde geloescht, bei Fragen dazu melde Dich bitte bei: " . variable_get('site_mail', 'Gemeinde-Buero unter info@elim-hamburg.de oder 040-2271970') . "<p>";
                }
            }
        }
    }
    if ($txt != "" && $buser != null) {
        $txt = "<h3>Hallo " . $buser->vorname . "!</h3><p>Deine Buchungsanfrage " . $info . $txt;
        if ($changes != null) {
            $txt .= "<p><b>Folgende Anpassung an der Buchung wurden vorgenommen:</b><br/>" . str_replace("\n", "<br>", $changes);
        }
        if ($params["status_id"] < 3) {
            $txt .= '<p><a class="btn" href="' . $base_url . "?q=churchresource&id=" . $params["id"] . '">Zur Buchungsanfrage &raquo;</a>';
        }
        $adminmails = explode(",", $ressources[$params["resource_id"]]->admin_person_ids);
        // Wenn der aktuelle User nicht Admin ist ODER wenn der Benutzer nicht der ist, der die Buchung erstellt hat.
        if (!in_array($user->id, $adminmails) || $user->id != $buser->id) {
            churchresource_send_mail("[" . variable_get('site_name', 'ChurchTools') . "] Aktualisierung der Buchungsanfrage: " . $params["text"], $txt, $buser->email);
        }
    }
    if ($changes != null) {
        cr_log("UPDATE BOOKING\n" . $txt, 3, $arr->id);
    }
    $res = array("exceptions" => $res_exceptions, "additions" => $res_additions);
    return $res;
}