/**
  * Saves item of agenda agenda_id
  *
  * @param array $params[...]
  * @return new item id
  */
 public function saveItem($params)
 {
     $agenda = $this->loadAgendas(array("ids" => array($params["agenda_id"])));
     if ($agenda == null) {
         throw new CTFail("Agenda nicht gefunden");
     }
     $this->checkPerm("edit agenda", null, $agenda[$params["agenda_id"]]->calcategory_id);
     if ($agenda[$params["agenda_id"]]->template_yn == 1) {
         $this->checkPerm("edit agenda templates", null, $agenda[$params["agenda_id"]]->calcategory_id);
     }
     $i = new CTInterface();
     $i->setParam("agenda_id");
     $i->setParam("bezeichnung");
     $i->setParam("header_yn");
     $i->setParam("responsible");
     $i->setParam("arrangement_id", false);
     $i->setParam("note");
     $i->setParam("sortkey");
     $i->setParam("duration");
     $i->setParam("preservice_yn");
     $i->addModifiedParams();
     if (empty($params["id"])) {
         $params["id"] = db_insert("cs_item")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
     } else {
         db_update("cs_item")->fields($i->getDBInsertArrayFromParams($params))->condition("id", $params["id"], "=")->execute(false);
     }
     if (isset($params["servicegroup"])) {
         foreach ($params["servicegroup"] as $key => $isg) {
             db_query("INSERT INTO {cs_item_servicegroup} (item_id, servicegroup_id, note)\n  \t              VALUES(:item_id, :servicegroup_id, :note)\n  \t              ON DUPLICATE KEY UPDATE note=:note", array(":item_id" => $params["id"], ":servicegroup_id" => $key, ":note" => $isg));
         }
     }
     // Now insert event-relation
     if (isset($params["event_ids"])) {
         foreach ($params["event_ids"] as $event_id) {
             // Ignore avoids errors when item is already mapped to event
             db_query("INSERT IGNORE INTO {cs_event_item} (event_id, item_id)\n                VALUES (:event_id, :item_id)", array(":event_id" => $event_id, ":item_id" => $params["id"]));
         }
     }
     return $params["id"];
 }
function churchcal_createEvent($params, $source = null)
{
    // Wenn es von anderem Modul kommt, habe ich da die Rechte schon gepr�ft!
    if ($source == null && !churchcal_isAllowedToEditCategory($params["category_id"])) {
        throw new CTNoPermission("Keine Rechte beim Erstellen mit Id:" . $params["category_id"], "churchcal");
    }
    $i = new CTInterface();
    $i->setParam("startdate");
    $i->setParam("enddate");
    $i->setParam("bezeichnung");
    $i->setParam("category_id");
    $i->setParam("repeat_id");
    $i->setParam("repeat_until", false);
    $i->setParam("repeat_frequence", false);
    $i->setParam("repeat_option_id", false);
    $i->setParam("intern_yn");
    $i->setParam("notizen");
    $i->setParam("link");
    $i->setParam("ort");
    $i->addModifiedParams();
    $new_id = db_insert("cc_cal")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
    if (isset($params["exceptions"])) {
        foreach ($params["exceptions"] as $exception) {
            $res = churchcal_addException(array("cal_id" => $new_id, "except_date_start" => $exception["except_date_start"], "except_date_end" => $exception["except_date_end"]));
        }
    }
    if (isset($params["additions"])) {
        foreach ($params["additions"] as $addition) {
            $res = churchcal_addAddition(array("cal_id" => $new_id, "add_date" => $addition["add_date"], "with_repeat_yn" => $addition["with_repeat_yn"]));
        }
    }
    // MeetingRequest
    if (isset($params["meetingRequest"])) {
        churchcal_handleMeetingRequest($new_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';
        $params["id"] = $new_id;
        churchresource_updateResourcesFromChurchCal($params, "churchcal");
    }
    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"] = $new_id;
        $cs_params["id"] = null;
        churchservice_createEventFromChurchCal($cs_params, $source);
    }
    return $new_id;
}
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;
}
/**
 * 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;
}
/**
 * Creates calender event and call other Modules
 *
 * @param array $params
 * @throws CTNoPermission
 * @return int; id of created event
 */
function churchcal_createEvent($params, $callCS = true, $withoutPerm = false)
{
    global $user, $base_url;
    // if source is another module rights are already checked
    if (!$withoutPerm && !churchcal_isAllowedToEditCategory($params["category_id"])) {
        throw new CTNoPermission(t('no.create.right.for.cal.id.x', $params["category_id"]), "churchcal");
    }
    $i = new CTInterface();
    $i->setParam("startdate");
    $i->setParam("enddate");
    $i->setParam("bezeichnung");
    $i->setParam("category_id");
    $i->setParam("repeat_id");
    $i->setParam("repeat_until", false);
    $i->setParam("repeat_frequence", false);
    $i->setParam("repeat_option_id", false);
    $i->setParam("intern_yn");
    $i->setParam("notizen");
    $i->setParam("link");
    $i->setParam("ort");
    $i->addModifiedParams();
    $params["id"] = db_insert("cc_cal")->fields($i->getDBInsertArrayFromParams($params))->execute(false);
    // Add exceptions
    if (!empty($params["exceptions"])) {
        foreach ($params["exceptions"] as $exception) {
            $res = churchcal_addException(array("cal_id" => $params["id"], "except_date_start" => $exception["except_date_start"], "except_date_end" => $exception["except_date_end"]));
        }
    }
    // Add additions
    if (!empty($params["additions"])) {
        foreach ($params["additions"] as $addition) {
            $res = churchcal_addAddition(array("cal_id" => $params["id"], "add_date" => $addition["add_date"], "with_repeat_yn" => $addition["with_repeat_yn"]));
        }
    }
    // Meeting request
    if (!empty($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);
        }
    }
    // Do Notification (abo)
    $data = db_query("select * from {cc_calcategory} where id=:id", array(":id" => $params["category_id"]))->fetch();
    $txt = $user->vorname . " " . $user->name . " hat im Kalender ";
    if ($data != false) {
        $txt .= $data->bezeichnung;
    } else {
        $txt .= $params["category_id"];
    }
    $txt .= " einen neuen Termin angelegt:<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) {
        if (getVar("informMe", "true") == "true" || getVar("informCreator", "true") == "true" && !empty($params["modified_pid"]) && $params["modified_pid"] != $user->id) {
            if (empty($params["modified_pid"])) {
                $params["modified_pid"] = $user->id;
            }
            $data = (array) churchcal_getEventChangeImpact(array("newEvent" => $params, "originEvent" => null, "pastEvent" => null));
            $data["new"] = true;
            $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" => $params["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($params["modified_pid"], "[" . getConf('site_name') . "] " . t2($lang, 'information.for.your.event'), $content, null, true);
        }
    }
    return array("id" => $params["id"], "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");
        }
    }
}