function churchwiki_setShowonstartpage($params)
{
    $i = new CTInterface();
    $i->setParam("doc_id");
    $i->setParam("version_no");
    $i->setParam("wikicategory_id");
    $i->setParam("auf_startseite_yn");
    db_update("cc_wiki")->fields($i->getDBInsertArrayFromParams($params))->condition("doc_id", $params["doc_id"], "=")->condition("version_no", $params["version_no"], "=")->condition("wikicategory_id", $params["wikicategory_id"], "=")->execute(false);
}
 public function editNotification($params)
 {
     global $user;
     if (empty($params["person_id"])) {
         $params["person_id"] = $user->id;
     }
     $i = new CTInterface();
     $i->setParam("domain_type");
     $i->setParam("domain_id");
     $i->setParam("person_id");
     $i->setParam("notificationtype_id", false);
     // Delete if abotype is not set
     if (empty($params["notificationtype_id"])) {
         db_delete("cc_notification")->fields($i->getDBInsertArrayFromParams($params))->condition("domain_type", $params["domain_type"], "=")->condition("domain_id", $params["domain_id"], "=")->condition("person_id", $user->id, "=")->execute(false);
     } else {
         try {
             db_insert("cc_notification")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
         } catch (Exception $e) {
             db_update("cc_notification")->fields($i->getDBInsertArrayFromParams($params))->condition("domain_type", $params["domain_type"], "=")->condition("domain_id", $params["domain_id"], "=")->condition("person_id", $user->id, "=")->execute(false);
         }
     }
 }
 public function deleteAgenda($params)
 {
     $agenda = $this->loadAgendas(array("ids" => array($params["id"])));
     if ($agenda == null) {
         throw new CTException("Agenda not found!");
     }
     $this->checkPerm("edit agenda", null, $agenda[$params["id"]]->calcategory_id);
     if (churchservice_isAgendaTemplate($params["id"])) {
         $this->checkPerm("edit agenda templates", null, $agenda[$params["id"]]->calcategory_id);
     }
     $i = new CTInterface();
     $i->setParam("id");
     $db = db_query("SELECT * FROM {cs_item} WHERE agenda_id=:agenda_id", array(":agenda_id" => $params["id"]), false);
     foreach ($db as $item) {
         $this->deleteItem(array("id" => $item->id));
     }
     db_delete("cs_agenda")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
 }
function churchcal_saveCategory($params)
{
    global $user;
    $id = null;
    if (isset($params["id"])) {
        $id = $params["id"];
    }
    $auth = false;
    if ($params["privat_yn"] == 1 && $params["oeffentlich_yn"] == 0) {
        if ($id != null) {
            $auth = user_access("admin personal category", "churchcal") || churchcal_iAmOwner($id);
        } else {
            $auth = user_access("admin personal category", "churchcal") || user_access("create personal category", "churchcal");
        }
    } else {
        if ($params["privat_yn"] == 0 && $params["oeffentlich_yn"] == 0) {
            if ($id != null) {
                $auth = user_access("admin group category", "churchcal") || churchcal_iAmOwner($id);
            } else {
                $auth = user_access("admin group category", "churchcal") || user_access("create group category", "churchcal");
            }
        } else {
            if ($params["privat_yn"] == 0 && $params["oeffentlich_yn"] == 1) {
                $auth = user_access("admin church category", "churchcal") || churchcal_iAmOwner($id);
            }
        }
    }
    if (!$auth) {
        throw new CTNoPermission("Admin edit category", "churchcal");
    }
    $i = new CTInterface();
    $i->setParam("bezeichnung");
    $i->setParam("sortkey");
    $i->setParam("color");
    $i->setParam("privat_yn");
    if (!isset($params["id"]) || $params["id"] == null) {
        // Offentlich wird nur beim Insert festgelegt
        $i->addModifiedParams();
        $i->setParam("oeffentlich_yn");
        $i->setParam("randomurl");
        $params["randomurl"] = random_string(32);
        $id = db_insert("cc_calcategory")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
        // Erg�nze noch das Recht f�r den Autor
        db_query("insert into {cc_domain_auth} (domain_type, domain_id, auth_id, daten_id)\n                  values ('person', {$user->id}, 404, {$id})");
        $_SESSION["user"]->auth = getUserAuthorization($_SESSION["user"]->id);
        if (isset($params["accessgroup"]) && $params["accessgroup"] != "") {
            if (isset($params["writeaccess"]) && $params["writeaccess"] == true) {
                db_query("insert into {cc_domain_auth} (domain_type, domain_id, auth_id, daten_id)\n                  values ('gruppe', " . $params["accessgroup"] . ", 404, {$id})");
            } else {
                db_query("insert into {cc_domain_auth} (domain_type, domain_id, auth_id, daten_id)\n                  values ('gruppe', " . $params["accessgroup"] . ", 403, {$id})");
            }
        }
    } else {
        $c = db_query("select * from {cc_calcategory} where id=:id", array(":id" => $params["id"]))->fetch();
        $id = $params["id"];
        db_update("cc_calcategory")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
    }
    return $id;
}
/**
 * Saves the reminder or delete if no reminddate is given. used by AJAX call
 * Please take care of authorization!!
 * @param unknown $params
 * @return multitype:unknown
 */
function churchcore_saveReminder($params)
{
    global $user;
    $params["person_id"] = $user->id;
    $id = null;
    $i = new CTInterface();
    $i->setParam("domain_id");
    $i->setParam("domain_type");
    $i->setParam("person_id");
    $i->setParam("reminddate", false);
    if (!isset($params["reminddate"])) {
        $id = db_delete("cc_reminder")->fields($i->getDBInsertArrayFromParams($params))->condition("person_id", $params["person_id"], "=")->condition("domain_id", db_cleanParam($params["domain_id"]), "=")->condition("domain_type", $params["domain_type"], "=")->execute(false);
    } else {
        $reminder = db_query("SELECT * FROM {cc_reminder} r\n                         WHERE person_id = :person_id AND domain_type = :domain_type\n                           AND domain_id = :domain_id", array(':person_id' => $params["person_id"], ':domain_type' => $params["domain_type"], ':domain_id' => $params["domain_id"]))->fetch();
        if (!$reminder) {
            $id = db_insert("cc_reminder")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
        } else {
            $id = $reminder->id;
            db_update("cc_reminder")->fields($i->getDBInsertArrayFromParams($params))->condition("person_id", $params["person_id"], "=")->condition("domain_id", db_cleanParam($params["domain_id"]), "=")->condition("domain_type", $params["domain_type"], "=")->execute(false);
        }
    }
    return array("id" => $id);
}
function churchcal_updateEvent($params, $source = null)
{
    $arr = array();
    // Store all Exception and Addition changes for communication to other modules
    $changes = array();
    // Nur Rechte pr�fen, wenn ich source bin, denn sonst hat das das Ursprungsmodul schon erledigt
    if ($source == null) {
        // Pr�fe, ob ich auf neue Kategorie schrieben darf
        if (!churchcal_isAllowedToEditCategory($params["category_id"])) {
            return CTNoPermission("AllowedToEditCategory[" . $params["category_id"] . "]", "churchcal");
        }
        // Pr�fe, ob ich auf die vorhandene Kategorie schreiben darf
        $old_cal = db_query("select category_id, startdate from {cc_cal} where id=:id", array(":id" => $params["id"]))->fetch();
        if (!churchcal_isAllowedToEditCategory($old_cal->category_id)) {
            return CTNoPermission("AllowedToEditCategory[" . $old_cal->category_id . "]", "churchcal");
        }
    }
    // Wenn es nur eine Verschiebung auf dem Kalender ist
    if (!isset($params["repeat_id"])) {
        $i = new CTInterface();
        $i->setParam("startdate", false);
        $i->setParam("enddate", false);
        $i->setParam("bezeichnung", false);
        $i->setParam("category_id", false);
        if (count($i->getDBInsertArrayFromParams($params)) > 0) {
            db_update("cc_cal")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute();
        }
    } else {
        $arr[":event_id"] = $params["id"];
        $arr[":startdate"] = $params["startdate"];
        $arr[":enddate"] = $params["enddate"];
        $arr[":bezeichnung"] = $params["bezeichnung"];
        $arr[":ort"] = $params["ort"];
        $arr[":intern_yn"] = $params["intern_yn"];
        $arr[":notizen"] = str_replace('\\"', '"', $params["notizen"]);
        $arr[":link"] = $params["link"];
        $arr[":category_id"] = $params["category_id"];
        if (isset($params["repeat_id"])) {
            $arr[":repeat_id"] = $params["repeat_id"];
        } else {
            $arr[":repeat_id"] = null;
        }
        if (isset($params["repeat_until"])) {
            $arr[":repeat_until"] = $params["repeat_until"];
        } else {
            $arr[":repeat_until"] = null;
        }
        if (isset($params["repeat_frequence"])) {
            $arr[":repeat_frequence"] = $params["repeat_frequence"];
        } else {
            $arr[":repeat_frequence"] = null;
        }
        if (isset($params["repeat_option_id"])) {
            $arr[":repeat_option_id"] = $params["repeat_option_id"];
        } else {
            $arr[":repeat_option_id"] = null;
        }
        db_query("update {cc_cal} set startdate=:startdate, enddate=:enddate, bezeichnung=:bezeichnung, ort=:ort,\n      notizen=:notizen, link=:link, category_id=:category_id, intern_yn=:intern_yn, category_id=:category_id, \n      repeat_id=:repeat_id, repeat_until=:repeat_until, repeat_frequence=:repeat_frequence,\n      repeat_option_id=:repeat_option_id \n        where id=:event_id", $arr);
        // Hole alle Exceptions aus der DB
        $exc = churchcore_getTableData("cc_cal_except", null, "cal_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) {
                if ($exception["id"] > 0) {
                    $exc[$exception["id"]]->vorhanden = true;
                } else {
                    $add_exc = array("cal_id" => $params["id"], "except_date_start" => $exception["except_date_start"], "except_date_end" => $exception["except_date_end"]);
                    churchcal_addException($add_exc);
                    $changes["add_exception"][] = $add_exc;
                }
            }
        }
        // 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)) {
                    $del_exc = array("id" => $e->id, "except_date_start" => $e->except_date_start, "except_date_end" => $e->except_date_end);
                    churchcal_delException($del_exc);
                    $changes["del_exception"][] = $del_exc;
                }
            }
        }
        // Hole alle Additions aus der DB
        $add = churchcore_getTableData("cc_cal_add", null, "cal_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) {
                if ($addition["id"] > 0) {
                    $add[$addition["id"]]->vorhanden = true;
                } else {
                    $add_add = array("cal_id" => $params["id"], "add_date" => $addition["add_date"], "with_repeat_yn" => $addition["with_repeat_yn"]);
                    churchcal_addAddition($add_add);
                    $changes["add_addition"][] = $add_add;
                }
            }
        }
        // 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)) {
                    $del_add = array("id" => $a->id, "add_date" => $a->add_date);
                    churchcal_delAddition($del_add);
                    $changes["del_addition"][] = $del_add;
                }
            }
        }
    }
    // MeetingRequest
    if (isset($params["meetingRequest"])) {
        churchcal_handleMeetingRequest($params["id"], $params);
    }
    // BENACHRICHTIGE ANDERE MODULE
    $modules = churchcore_getModulesSorted(false, false);
    if (in_array("churchresource", $modules) && ($source == null || $source != "churchresource")) {
        include_once CHURCHRESOURCE . '/churchresource_db.php';
        if ($source == null) {
            $source = "churchcal";
        }
        $params["cal_id"] = $params["id"];
        churchresource_updateResourcesFromChurchCal($params, $source, $changes);
    }
    if (in_array("churchservice", $modules) && ($source == null || $source != "churchservice")) {
        include_once CHURCHSERVICE . '/churchservice_db.php';
        $cs_params = array_merge(array(), $params);
        $cs_params["cal_id"] = $params["id"];
        $cs_params["id"] = null;
        $cs_params["old_startdate"] = $old_cal->startdate;
        if ($source == null) {
            $source = "churchcal";
        }
        churchservice_updateEventFromChurchCal($cs_params, $source);
    }
}
Beispiel #7
0
/**
 * save cal category
 * @param array $params
 * @throws CTNoPermission
 * @return Ambigous <mixed, string>
 */
function churchcal_saveCategory($params)
{
    global $user;
    $id = getVar('id', false, $params);
    $auth = false;
    if ($params["privat_yn"] == 1 && $params["oeffentlich_yn"] == 0) {
        if ($id) {
            $auth = user_access("admin personal category", "churchcal") || churchcal_isUserOwnerOf($id);
        } else {
            $auth = user_access("admin personal category", "churchcal") || user_access("create personal category", "churchcal");
        }
    } else {
        if ($params["privat_yn"] == 0 && $params["oeffentlich_yn"] == 0) {
            if ($id) {
                $auth = user_access("admin group category", "churchcal") || churchcal_isUserOwnerOf($id);
            } else {
                $auth = user_access("admin group category", "churchcal") || user_access("create group category", "churchcal");
            }
        } else {
            if ($params["privat_yn"] == 0 && $params["oeffentlich_yn"] == 1) {
                $auth = user_access("admin church category", "churchcal") || churchcal_isUserOwnerOf($id);
            }
        }
    }
    if (!$auth) {
        throw new CTNoPermission("Admin edit category", "churchcal");
    }
    $i = new CTInterface();
    $i->setParam("bezeichnung");
    $i->setParam("sortkey");
    $i->setParam("color");
    $i->setParam("privat_yn");
    $i->setParam("ical_source_url", false);
    if (!$id) {
        // oeffentlich will be set on insert only
        $i->addModifiedParams();
        $i->setParam("oeffentlich_yn");
        $i->setParam("randomurl");
        $params["randomurl"] = random_string(32);
        $id = db_insert("cc_calcategory")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
        // add rights for author
        db_query("INSERT INTO {cc_domain_auth} (domain_type, domain_id, auth_id, daten_id)\n              VALUES ('person', :userId, 404, :id)", array(':userId' => $user->id, ':id' => $id));
        $_SESSION["user"]->auth = getUserAuthorization($_SESSION["user"]->id);
        if (getVar('accessgroup', false, $params)) {
            db_query("INSERT INTO {cc_domain_auth} (domain_type, domain_id, auth_id, daten_id)\n                VALUES ('gruppe', :accessgroup, :auth, :id)", array(':accessgroup' => $params["accessgroup"], ':auth' => getVar('writeaccess', false, $params) == true ? 404 : 403, ':id' => $id));
        }
    } else {
        $c = db_query("SELECT * FROM {cc_calcategory}\n                   WHERE id=:id", array(":id" => $id))->fetch();
        db_update("cc_calcategory")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $id, "=")->execute(false);
    }
    if (!empty($params["ical_source_url"])) {
        churchcal_updateICalSource($id);
    }
    return $id;
}
/**
 * add mail chimp relation
 * 
 * @param array $params
 * @return last insert id
 */
function churchdb_addMailchimpRelation($params)
{
    $i = new CTInterface();
    $i->setParam("gruppe_id");
    $i->setParam("mailchimp_list_id");
    $i->setParam("optin_yn");
    $i->setParam("goodbye_yn");
    $i->setParam("notifyunsubscribe_yn");
    $i->addModifiedParams();
    $res = db_insert("cdb_gruppe_mailchimp")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
    return $res;
}
/**
 * Store all Exception and Addition changes for communication to other modules
 *
 * @param array $params
 * @param string $sourc; controls cooperation between modules if event comes from another modulee
 * @param boolean $withoutPerm If permission will be checked.
 */
function churchcal_updateEvent($params, $callCS = true, $withoutPerm = false)
{
    global $user, $base_url;
    $changes = array();
    if (!$withoutPerm && !churchcal_isAllowedToEditCategory($params["category_id"])) {
        throw new CTNoPermission("AllowedToEditCategory[" . $params["category_id"] . "] (newCat)", "churchcal");
    }
    $old_cal = db_query("SELECT *\n                       FROM {cc_cal}\n                       WHERE id=:id", array(":id" => $params["id"]))->fetch();
    // can user edit old event category?
    if (!$withoutPerm && !churchcal_isAllowedToEditCategory($old_cal->category_id)) {
        throw new CTNoPermission("AllowedToEditCategory[" . $old_cal->category_id . "] (oldCat)", "churchcal");
    }
    // When empty, load originEvent for later sending Change protocol
    $dummy = churchcal_getCalPerCategory(array("category_ids" => array(0 => $old_cal->category_id)));
    $originEvent = (array) $dummy[$old_cal->category_id][$params["id"]];
    if (isset($params["notizen"])) {
        $params["notizen"] = str_replace('\\"', '"', $params["notizen"]);
    }
    $i = new CTInterface();
    $i->setParam("startdate", false);
    $i->setParam("enddate", false);
    $i->setParam("bezeichnung", false);
    $i->setParam("category_id", false);
    $i->setParam("ort", false);
    $i->setParam("notizen", false);
    $i->setParam("intern_yn", false);
    $i->setParam("link", false);
    $i->setParam("repeat_id", false);
    $i->setParam("repeat_until", false);
    $i->setParam("repeat_frequence", false);
    $i->setParam("repeat_option_id", false);
    if (isset($params["modified_pid"])) {
        $i->setParam("modified_pid");
    }
    // not with ", false" cause this cause an update
    $f = $i->getDBInsertArrayFromParams($params);
    if (count($f)) {
        db_update("cc_cal")->fields($f)->condition("id", $params["id"], "=")->execute();
    }
    // get all exceptions for event
    $exc = churchcore_getTableData("cc_cal_except", null, "cal_id=" . $params["id"]);
    // look which are already in DB
    if (!empty($params["exceptions"])) {
        foreach ($params["exceptions"] as $exception) {
            if ($exception["id"] > 0) {
                $exc[$exception["id"]]->vorhanden = true;
            } else {
                $add_exc = array("cal_id" => $params["id"], "except_date_start" => $exception["except_date_start"], "except_date_end" => $exception["except_date_end"]);
                churchcal_addException($add_exc);
                $changes["add_exception"][] = $add_exc;
            }
        }
    }
    // delete removed exceptions from DB
    if ($exc) {
        foreach ($exc as $e) {
            if (!isset($e->vorhanden)) {
                $del_exc = array("id" => $e->id, "except_date_start" => $e->except_date_start, "except_date_end" => $e->except_date_end);
                churchcal_delException($del_exc);
                $changes["del_exception"][] = $del_exc;
            }
        }
    }
    // get all additions
    $add = churchcore_getTableData("cc_cal_add", null, "cal_id=" . $params["id"]);
    // look which are already in DB.
    if (!empty($params["additions"])) {
        foreach ($params["additions"] as $addition) {
            if ($addition["id"] > 0) {
                $add[$addition["id"]]->vorhanden = true;
            } else {
                $add_add = array("cal_id" => $params["id"], "add_date" => $addition["add_date"], "with_repeat_yn" => $addition["with_repeat_yn"]);
                churchcal_addAddition($add_add);
                $changes["add_addition"][] = $add_add;
            }
        }
    }
    // delete from DB which are deleted.
    if ($add) {
        foreach ($add as $a) {
            if (!isset($a->vorhanden)) {
                $del_add = array("id" => $a->id, "add_date" => $a->add_date);
                churchcal_delAddition($del_add);
                $changes["del_addition"][] = $del_add;
            }
        }
    }
    // meeting request
    if (isset($params["meetingRequest"])) {
        churchcal_handleMeetingRequest($params["id"], $params);
    }
    // Call other modules
    $newBookingIds = null;
    if (churchcore_isModuleActivated("churchresource")) {
        include_once CHURCHRESOURCE . '/churchresource_db.php';
        $newBookingIds = churchresource_operateResourcesFromChurchCal($params);
    }
    $newCSIds = null;
    if ($callCS) {
        if (churchcore_isModuleActivated("churchservice")) {
            include_once CHURCHSERVICE . '/churchservice_db.php';
            $newCSIds = churchservice_operateEventFromChurchCal($params);
        }
    }
    // Notification
    $data = db_query("select * from {cc_calcategory} where id=:id", array(":id" => $params["category_id"]))->fetch();
    $txt = $user->vorname . " " . $user->name . " hat einen Termin angepasst im Kalender ";
    if ($data != false) {
        $txt .= $data->bezeichnung;
    } else {
        $txt .= $params["category_id"];
    }
    $txt .= " auf:<br>";
    $txt .= churchcore_CCEventData2String($params);
    ct_notify("category", $params["category_id"], $txt);
    // Inform creator when I am allowed and when it is not me!
    if ($callCS && getVar("informCreator", "true") == "true" && $originEvent["modified_pid"] != $user->id) {
        $data = (array) churchcal_getEventChangeImpact(array("newEvent" => $params, "originEvent" => $originEvent, "pastEvent" => null));
        if (!empty($data["bookings"]) || !empty($data["cal"])) {
            $data["new"] = false;
            $data["caption"] = $params["bezeichnung"];
            $data["startdate"] = churchcore_stringToDateDe($params["startdate"]);
            $data["eventUrl"] = $base_url . "?q=churchcal&category_id=" . $params["category_id"] . "&id=" . $params["id"];
            $p = db_query("SELECT name, vorname, IF(spitzname, spitzname, vorname) AS nickname\n                      FROM {cdb_person}\n                      WHERE id=:id", array(":id" => $originEvent["modified_pid"]))->fetch();
            $data["p"] = $p;
            // get populated template and send email
            $lang = getUserLanguage($params["modified_pid"]);
            $content = getTemplateContent('email/informCreator', 'churchcal', $data, null, $lang);
            churchcore_sendEMailToPersonIDs($originEvent["modified_pid"], "[" . getConf('site_name') . "] " . t2($lang, 'information.for.your.event'), $content, null, true);
        }
    }
    return array("cseventIds" => $newCSIds, "bookingIds" => $newBookingIds);
}
/**
 * edit person weight for service group (for auto planning?)
 * @param array $params
 */
function churchservice_editServiceGroupPersonWeight($params)
{
    $i = new CTInterface();
    $i->setParam("servicegroup_id");
    $i->setParam("person_id");
    $i->setParam("max_per_month");
    $i->setParam("relation_weight");
    $i->setParam("morning_weight");
    $i->addModifiedParams();
    try {
        db_insert("cs_servicegroup_person_weight")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
    } catch (Exception $e) {
        db_query("UPDATE {cs_servicegroup_person_weight} \n        SET max_per_month=:max_per_month, relation_weight=:relation_weight, morning_weight=:morning_weight\n        WHERE servicegroup_id=:servicegroup_id and person_id=:person_id", $i->getDBParamsArrayFromParams($params));
    }
}
/**
 *
 * @param array $params          
 * @throws CTException
 */
function savePropertiesGroupMeetingStats($params)
{
    $i = new CTInterface();
    $i->setParam("id");
    $i->setParam("anzahl_gaeste");
    $i->setParam("kommentar");
    $i->setParam("datumvon", false);
    $i->setParam("datumbis", false);
    $i->addModifiedParams();
    $id = db_update("cdb_gruppentreffen")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
    if (isset($params["entries"])) {
        if (entryGroupMeeting($params["g_id"], $params["id"], $params["entries"]) != "ok") {
            throw new CTException("Problem beim Speichern der einzelnen Teilnahmerdaten");
        }
    }
}
/**
 * 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);
}
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;
}