Files

976 lines
42 KiB
PHP
Raw Permalink Normal View History

<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
$languageCode = isset($_GET['language']) ? $_GET['language'] : 'de';
$languageCode = mysqli_real_escape_string($GLOBALS['mysql_con'], $languageCode);
$languageId = $GLOBALS['language']['id'] ?? 1;
$isEmbedded = (isset($_GET['embedded']) && $_GET['embedded'] == 1) ? 1 : 0;
// Dependencies einbinden
require_once(__DIR__ . '/../Dependencies/Dependencies.php');
require_once(__DIR__ . '/../Middleware/Middleware.php');
if ($_COOKIE['recaptcha'] == 1) { ?>
<script src='https://www.google.com/recaptcha/api.js'></script>
<?
}
$c_form = "";
foreach ($_GET as $key => $value) {
if (preg_match('/^c_form\d+$/', $key)) {
// Do something with $key and $value
$c_form = $key;
}
}
$translation = \DynCom\mysyde\common\classes\Registry::get("translation");
$spid = 0;
$userId = 0;
$addUser = FALSE;
if (isset($_GET[$c_form]) && !empty($_POST)) {
$sitepart_id = $_GET[$c_form];
$queryFormData = "SELECT * FROM contactform_header WHERE id = '" . $sitepart_id . "'";
$resultFormData = @mysqli_query($GLOBALS['mysql_con'], $queryFormData);
$contactFormData = @mysqli_fetch_array($resultFormData);
$header_id = $contactFormData['id'];
// var_dump($header_id);
// echo "test";
$requestmassage = "";
$success = false;
$_REQUEST['input_contactform'] = $header_id;
// daten sammeln
$query = "SELECT * FROM contactform_header WHERE id = '" . $sitepart_id . "'";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
$contactform_header = @mysqli_fetch_array($result);
$filetypeError = FALSE;
$error = FALSE;
$captchError = FALSE;
$message = "";
/** Neu Abfrage aus welcher Seite Anfrage geschickt wurde */
$navigation_pfad = $_SERVER['HTTP_HOST'];
$navigation_pfad .= navigation_path($GLOBALS["site"], $GLOBALS["language"], $GLOBALS["navigation"]);
// $navigation_pfad .= $_SERVER['REQUEST_URI'];
$ajaxHelper = "";
if (isset($_GET['ajax'])) {
$ajaxHelper = "~|~";
}
//recaptcha
if ($contactform_header['recaptcha_active'] == 1) {
$secretKey = $GLOBALS['site']['secretkey'];
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$data = json_decode($response);
if ($data->success == FALSE) {
$error = TRUE;
$captchError = TRUE;
}
}
$query = "SELECT * FROM contactform_line WHERE header_id = '" . $sitepart_id . "' ORDER BY sorting ASC";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
if (@mysqli_num_rows($result) > 0) {
// Initialize helpers
unset($field_errors);
$field_errors = [];
$attachements = []; // raw filenames in /userdata/mail_attachments/
$file = []; // final paths for mail_create
$submission_data = [];
$filetypeError = FALSE;
$error = FALSE;
// contact form linked in collection (keep your existing logic)
if (
isset($_POST['contact_field_id'], $_POST['main_collection_id']) &&
$_POST['contact_field_id'] != 0 && $_POST['main_collection_id'] != 0
) {
$queryLinked = "SELECT * FROM main_collection_contact_linked WHERE main_collection_id = " . (int) $_POST['main_collection_id'] . " AND field_id = " . (int) $_POST['contact_field_id'];
$resultLinked = @mysqli_query($GLOBALS['mysql_con'], $queryLinked);
if (@mysqli_num_rows($resultLinked) > 0) {
$row = @mysqli_fetch_array($resultLinked);
$contactform_header["recipient_email"] = $row['receiver_email'];
$contactform_header["recipient_name"] = $row['receiver_name'];
}
$queryCollection = "SELECT mc.*, mcs.collection_type FROM main_collection as mc INNER JOIN main_collection_setup as mcs on mc.main_collection_setup_id = mcs.id WHERE mc.id = '" . (int) $_POST['main_collection_id'] . "' ";
$resultCollection = @mysqli_query($GLOBALS['mysql_con'], $queryCollection);
if (@mysqli_num_rows($resultCollection) > 0) {
$collection = @mysqli_fetch_array($resultCollection);
if ((int) $collection['collection_type'] === 2) {
$queryLinked = "SELECT * FROM bewerbung WHERE main_collection_id = " . (int) $_POST['main_collection_id'] . " AND contact_id = " . (int) $header_id . " AND user_id = " . (int) $userId;
$resultLinked = @mysqli_query($GLOBALS['mysql_con'], $queryLinked);
if (@mysqli_num_rows($resultLinked) > 0) {
$addUser = FALSE;
$error = TRUE;
$requestmassage .= "<div class=\"danger infobox\">" . $translation->get('user_exist') . "<br></div>";
} else {
$queryInsert = "INSERT INTO bewerbung (contact_id,user_id,main_collection_id, modified_date)
VALUES ('" . (int) $header_id . "', '" . (int) $userId . "', '" . (int) $_POST['main_collection_id'] . "', '" . time() . "')";
$addUser = TRUE;
@mysqli_query($GLOBALS['mysql_con'], $queryInsert);
}
}
}
}
// Iterate all fields and build message + attachments + submission_data
while ($field = @mysqli_fetch_array($result)) {
$field_id = (int) $field['id'];
$field_code = $field['code']; // may be null in legacy data
$input_key = "input_" . ($field_code ?? $field_id);
$input_value = $_POST[$input_key] ?? '';
$linked_value = '';
// Basic mandatory check (skip special cases & file types)
if (
($field["code"] !== 'registration_name' && $field["code"] !== 'registration_email') &&
empty($_POST[$input_key]) &&
!empty($field["mandatory"]) &&
// skip file(8), radio(10) special handling in their cases
($field["typ"] != 8 && $field["typ"] != 10)
) {
$error = TRUE;
$field_errors[] = $field_id;
}
// --- FULL SWITCH-CASE ---
switch ($field["typ"]) {
case 1: // Single-line text
if ($field['code'] === 'subject' && isset($_POST[$input_key])) {
$contactform_header["subject"] = trim((string) $_POST[$input_key]);
}
$val = $_POST[$input_key] ?? '';
$message .= "<strong>" . $field["name"] . ":</strong> " . $val . "\n";
$input_value = $val;
$linked_value = '';
break;
case 2: // Multiline textarea
$raw = $_POST[$input_key] ?? '';
// Normalize newlines for mail rendering
$search = array('\r\n', '\n\r', '\r', '\n');
$replace = array(PHP_EOL, PHP_EOL, PHP_EOL, PHP_EOL);
$clean = str_replace($search, $replace, $raw);
$message .= "<strong>" . $field["name"] . ":</strong> " . $clean . "\n";
$input_value = $clean;
$linked_value = '';
break;
case 3: // Boolean (checkbox)
$checked = !empty($_POST[$input_key]);
$boolText = $checked ? "Ja" : "Nein";
$message .= "<strong>" . $field["name"] . ":</strong> " . $boolText . "\n";
$input_value = $checked ? '1' : '0';
$linked_value = '';
break;
case 4: // Select / special codes (mandant, user)
if ($field['code'] === 'mandant') {
// Hidden/system value — not printed, but stored
$input_value = $_POST[$input_key] ?? '';
$linked_value = '';
break;
} elseif ($field['code'] === 'user') {
$username = $GLOBALS['main_contact']['name'] ?? '';
$message .= "<strong>" . $field["name"] . ":</strong> " . $username . "\n";
$input_value = $username;
$linked_value = '';
break;
} else {
$val = $_POST[$input_key] ?? '';
$message .= "<strong>" . $field["name"] . ":</strong> " . $val . "\n";
$input_value = $val;
$linked_value = '';
}
// Linked fields for multistep/survey (optional free-text per option)
if (!empty($contactFormData['is_multistep']) || !empty($contactFormData['is_survey'])) {
$qOpt = 'SELECT * FROM contactform_line_option WHERE line_id = ' . $field_id;
$resOpt = @mysqli_query($GLOBALS['mysql_con'], $qOpt);
if ($resOpt) {
while ($opt = @mysqli_fetch_array($resOpt)) {
if (!empty($opt['linked_field'])) {
$lk = "inputlinked_" . $field_id . '_' . (int) $opt['id'];
if (isset($_POST[$lk]) && $_POST[$lk] !== '') {
$message .= $_POST[$lk] . "\n";
$linked_value = $_POST[$lk]; // store last linked input
}
}
}
}
}
break;
case 5: // Static label/header
$message .= "<strong>" . $field["name"] . "</strong>\n";
$input_value = ''; // purely presentational
$linked_value = '';
break;
case 6: // Separator / line break
$message .= "\n";
$input_value = '';
$linked_value = '';
break;
case 7: // Title taken from input
$val = $_POST[$input_key] ?? '';
$message .= "<strong>" . $val . "</strong>\n";
$input_value = $val;
$linked_value = '';
break;
case 8: // File upload (single or multiple)
// Ensure arrays exist
if (!isset($attachements) || !is_array($attachements)) {
$attachements = [];
}
// HTML input name expected as "input_<code>" or "input_<code>[]"
$uploadField = $input_key;
// Normalize $_FILES to array of file hashes
$files = [];
if (isset($_FILES[$uploadField])) {
if (is_array($_FILES[$uploadField]['name'])) {
$cnt = count($_FILES[$uploadField]['name']);
for ($i = 0; $i < $cnt; $i++) {
$files[] = [
'name' => $_FILES[$uploadField]['name'][$i],
'type' => $_FILES[$uploadField]['type'][$i],
'tmp_name' => $_FILES[$uploadField]['tmp_name'][$i],
'error' => $_FILES[$uploadField]['error'][$i],
'size' => $_FILES[$uploadField]['size'][$i],
];
}
} else {
$files[] = $_FILES[$uploadField];
}
}
// Mandatory check for files
if ((empty($files) || ($files[0]['name'] ?? '') === '') && !empty($field["mandatory"])) {
$error = TRUE;
$input_value = '';
$linked_value = '';
break;
}
if (empty($files) || ($files[0]['name'] ?? '') === '') {
// No files and not mandatory
$input_value = '';
$linked_value = '';
break;
}
// Target directory
$uploadDir = rtrim(dirname(dirname(dirname(__DIR__))), "/") . '/userdata/mail_attachments/';
if (!is_dir($uploadDir)) {
@mkdir($uploadDir, 0775, true);
}
// Extension policies
$allowed = ['pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'zip', 'rar', '7z', 'txt', 'csv', 'mp4', 'mov', 'avi', 'mkv'];
$blocked = ['php', 'phtml', 'phar', 'cgi', 'pl', 'exe', 'sh', 'bat', 'cmd', 'com', 'js', 'msi'];
$uploadedNames = [];
foreach ($files as $f) {
// Skip unsuccessful items
if (!isset($f['error']) || $f['error'] !== UPLOAD_ERR_OK || ($f['name'] ?? '') === '') {
continue;
}
$ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
if (in_array($ext, $blocked, true) || ($ext !== '' && !in_array($ext, $allowed, true))) {
$filetypeError = TRUE;
$error = TRUE;
continue;
}
// Optional: size limit (e.g., 25MB)
// if (($f['size'] ?? 0) > 25 * 1024 * 1024) { $filetypeError = TRUE; $error = TRUE; continue; }
// Sanitize filename & ensure uniqueness
$base = preg_replace('/[^A-Za-z0-9._-]+/', '_', $f['name']);
$dest = $uploadDir . $base;
$iUniq = 1;
$extSuffix = $ext ? ('.' . $ext) : '';
while (file_exists($dest)) {
$stem = pathinfo($base, PATHINFO_FILENAME);
$dest = $uploadDir . $stem . "_" . $iUniq . $extSuffix;
$iUniq++;
}
if (@move_uploaded_file($f['tmp_name'], $dest)) {
$attachements[] = basename($dest);
$uploadedNames[] = basename($dest);
} else {
$filetypeError = TRUE;
$error = TRUE;
}
}
// Mark field value & show list in message
$input_value = $uploadedNames ? 'FILE_ATTACHMENT' : '';
$linked_value = '';
if (!empty($uploadedNames)) {
$message .= "<strong>" . $field["name"] . ":</strong> " . implode(', ', $uploadedNames) . "\n";
}
break;
case 9: // Checkbox group (multi-select) — uses field id in POST
$vals = $_POST["input_" . $field_id] ?? null;
if (is_array($vals) && !empty($vals)) {
$lines = implode('<br>', array_map('trim', $vals));
$message .= "<strong>" . $field["name"] . ":</strong><br>" . $lines . "\n";
$input_value = implode(', ', $vals);
} else {
$input_value = '';
}
$linked_value = '';
// Linked inputs per chosen option (multistep)
if (!empty($contactFormData['is_multistep'])) {
$qOpt = 'SELECT * FROM contactform_line_option WHERE line_id = ' . $field_id;
$resOpt = @mysqli_query($GLOBALS['mysql_con'], $qOpt);
if ($resOpt) {
while ($opt = @mysqli_fetch_array($resOpt)) {
if (!empty($opt['linked_field'])) {
$lk = "inputlinked_" . $field_id . '_' . (int) $opt['id'];
if (isset($_POST[$lk]) && $_POST[$lk] !== '') {
$message .= $_POST[$lk] . "\n";
$linked_value = $_POST[$lk];
}
}
}
}
}
break;
case 10: // Single choice (radio/select) — uses field id in POST
$chosen = $_POST["input_" . $field_id] ?? '';
if ($chosen !== '') {
$message .= "<strong>" . $field["name"] . ":</strong> " . $chosen . "\n";
}
$input_value = $chosen;
$linked_value = '';
// Linked input for selected option (multistep/survey)
if (!empty($contactFormData['is_multistep']) || !empty($contactFormData['is_survey'])) {
$qOpt = 'SELECT * FROM contactform_line_option WHERE line_id = ' . $field_id;
$resOpt = @mysqli_query($GLOBALS['mysql_con'], $qOpt);
if ($resOpt) {
while ($opt = @mysqli_fetch_array($resOpt)) {
if ($opt['option_string'] === $chosen && !empty($opt['linked_field'])) {
$lk = "inputlinked_" . $field_id . '_' . (int) $opt['id'];
if (isset($_POST[$lk]) && $_POST[$lk] !== '') {
$message .= $_POST[$lk] . "\n";
$linked_value = $_POST[$lk];
}
break;
}
}
}
}
break;
case 11: // Date
$raw = $_POST[$input_key] ?? '';
$formatted = '';
if ($raw !== '') {
try {
$dt = new DateTime($raw);
$formatted = $dt->format('d.m.Y');
} catch (Throwable $e) {
$formatted = $raw; // fallback
}
}
$message .= "<strong>" . $field["name"] . ":</strong> " . $formatted . "\n";
$input_value = $raw; // store raw in DB
$linked_value = '';
break;
default:
// Unknown type — store raw if present
$val = $_POST[$input_key] ?? '';
if ($val !== '') {
$message .= "<strong>" . $field["name"] . ":</strong> " . $val . "\n";
}
$input_value = $val;
$linked_value = '';
break;
}
// Persist a normalized snapshot of the user's input for each field
$submission_data[] = [
'field_id' => $field_id,
'value' => is_array($input_value) ? implode(', ', $input_value) : (string) $input_value,
'linked_value' => is_array($linked_value) ? implode(', ', $linked_value) : (string) $linked_value,
];
}
}
if (($_POST["input_captcha1"] <> "") | ((time() - $_POST["input_captcha2"]) < 5)) {
$error = TRUE;
$requestmassage .= $GLOBALS['tc']['contactform_spam'];
}
if ($captchError == TRUE) {
echo $ajaxHelper . "<div class=\"danger infobox\">Bitte verwenden Sie das Captcha <br></div>" . $ajaxHelper;
} else {
echo $ajaxHelper . "" . $ajaxHelper;
}
if ($filetypeError === true) {
echo $ajaxHelper . "<div class=\"danger infobox\">Upload von PHP Dateien nicht erlaubt</div>" . $ajaxHelper;
}
//DUP breadcrumb upload mehrere Dateien update
if (!$error) {
//fügt Daten ins Array
foreach ($attachements as $attachement_line) {
$file[] = "/userdata/mail_attachments/" . $attachement_line;
}
// AUTOMATISCHE ANTWORT
if ($contactform_header["auto_answer"] != "" && $GLOBALS['main_contact']['email'] != "") {
if (
mail_create(
$contactform_header["subject"],
$contactform_header["auto_answer"],
$contactform_header["sender_email"],
$GLOBALS['main_contact']['email'],
$contactform_header["sender_name"],
$GLOBALS['main_contact']['email'],
FALSE,
"",
"",
"",
0,
"",
"",
$contact_form_id
)
) {
mail_send();
clearstatcache();
$success = true;
$requestmassage .= $GLOBALS['tc']['contactform_success'];
foreach ($_POST as $key => $value) {
unset($_POST[$key]);
}
} else {
$error = TRUE;
$requestmassage .= $translation->get('not_send1');
}
}
if ($sitepart_id == 1) {
$mandant_id = $GLOBALS["main_contact"]['master_mandant_id'];
$contact_id = $GLOBALS["main_contact"]['id'];
// $query = "SELECT * FROM main_contact_link LEFT JOIN main_collection as mc on mc.id = plg.portal_group_id WHERE plg.portal_login_id ='".$login_id."' AND plg.portal_group_id = '".$group_id."' AND plg.email != ''";
// $result = @mysqli_query($GLOBALS['mysql_con'], $query);
// $res = mysqli_fetch_array($result);
$contactform_header2["sender_email"] = $contactform_header["sender_email"];
$contactform_header2["sender_name"] = $contactform_header["sender_name"];
$contactform_header["sender_email"] = $GLOBALS["main_contact"]['email'];
$contactform_header["sender_name"] = $GLOBALS["main_contact"]['name'];
$contactform_header["subject"] = "Abwesenheit | {$GLOBALS["main_contact"]['name']}";
}
if ($sitepart_id == 2) {
$contactform_header["sender_email"] = $GLOBALS["main_contact"]['email'];
$contactform_header["sender_name"] = $GLOBALS["main_contact"]['name'];
$query = 'SELECT * from main_contact WHERE id = ' . $_REQUEST['input_user'] . ' LIMIT 1';
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
if (@mysqli_num_rows($result) == 1) {
$user = @mysqli_fetch_array($result);
if ($user['email'] != NULL && $user['email'] != '') {
$contactform_header["recipient_name"] = $user['name'];
$contactform_header["recipient_email"] = $user['email'];
}
}
create_notification($_REQUEST['input_user'], $message);
}
// Sende E-Mail an Firmen-Email
if ($sitepart_id == 1) {
$query = "SELECT * FROM main_contact_department WHERE main_contact_id = '" . $GLOBALS["main_contact"]['id'] . "' AND sorting = 1";
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
$input_arbeitsunfaehigkeitsbescheinigung = $_POST['input_arbeitsunfaehigkeitsbescheinigung'];
$input_date2 = new DateTime($_POST['input_date2']);
$input_date = new DateTime($_POST['input_date']);
$input_besprechung = $_POST['input_besprechung'];
$input_ansprechpartner = $_POST['input_ansprechpartner'];
while ($res = mysqli_fetch_array($result)) {
$query = "SELECT * FROM main_mandant WHERE id = " . $res['main_mandant_id'];
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
$res_mandant = @mysqli_fetch_array($result);
$contactform_header2['recipient_email'] = $res_mandant['mail_team'];
$contactform_header2['recipient_name'] = $res_mandant['description'];
$message2 = "Liebes Team, \n\n";
if (isset($_POST['serial_code']) && $_POST['serial_code'] != "") {
$randomString = $_POST['serial_code'];
} else {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
}
if (isset($input_arbeitsunfaehigkeitsbescheinigung) && $input_date2 != "") {
$message2 .= $GLOBALS["main_contact"]['name'] . " ist bis einschließlich den " . $input_date2->format('d.m.Y') . " abwesend.\n";
$check_query = "SELECT events_type.id, events_type.sick_note FROM events_type WHERE events_type.sick_note = 1";
$check_result = mysqli_query($GLOBALS['mysql_con'], $check_query);
$check_row = mysqli_fetch_assoc($check_result);
$event_type_id = $check_row["id"];
$created_date = date(format: "Y-m-d H:i:s");
$modifiedDate = date(format: "Y-m-d H:i:s");
$date = clone $input_date;
while ($date <= $input_date2) {
$delete_query = "DELETE FROM events WHERE date_from = '" . $date->format('Y-m-d') . "' AND main_contact_id = '" . $GLOBALS['main_contact']['id'] . "'";
@mysqli_query($GLOBALS['mysql_con'], $delete_query);
$insert_query = "INSERT INTO events (
date_from,
date_to,
main_contact_id,
event_type_id,
serial_code,
created_date,
modified_date,
all_day,
active
) VALUES (
'" . $date->format('Y-m-d') . "',
'" . $date->format('Y-m-d') . "',
'" . $GLOBALS['main_contact']['id'] . "',
'" . $event_type_id . "',
'" . $randomString . "',
'" . $created_date . "',
'" . $modifiedDate . "',
1,
1
)";
@mysqli_query($GLOBALS['mysql_con'], $insert_query);
$date->modify('+1 day');
}
} else {
$message2 .= $GLOBALS["main_contact"]['name'] . " hat sich für den " . $input_date->format('d.m.Y') . " abgemeldet.\n";
$delete_query = "DELETE FROM events WHERE date_from = '" . $input_date->format('Y-m-d') . "' AND main_contact_id = '" . $GLOBALS['main_contact']['id'] . "'";
@mysqli_query($GLOBALS['mysql_con'], $delete_query);
$check_query = "SELECT events_type.id, events_type.sick_note FROM events_type WHERE events_type.sick_note = 1";
$check_result = mysqli_query($GLOBALS['mysql_con'], $check_query);
$check_row = mysqli_fetch_assoc($check_result);
$event_type_id = $check_row["id"];
$created_date = date(format: "Y-m-d H:i:s");
$modifiedDate = date(format: "Y-m-d H:i:s");
$insert_query = "INSERT INTO events (
date_from,
date_to,
main_contact_id,
event_type_id,
serial_code,
created_date,
modified_date,
all_day,
active
) VALUES (
'" . $date->format('Y-m-d') . "',
'" . $date->format('Y-m-d') . "',
'" . $GLOBALS['main_contact']['id'] . "',
'" . $event_type_id . "',
'" . $randomString . "',
'" . $created_date . "',
'" . $modifiedDate . "',
1,
1
)";
@mysqli_query($GLOBALS['mysql_con'], $insert_query);
}
if (isset($input_besprechung) && $input_ansprechpartner != "") {
$message2 .= "Die telefonische Besprechung zur Übergabe von Aufgaben und Terminen erfolgte mit " . $input_ansprechpartner . ".\n";
}
if (
mail_create(
$contactform_header["subject"],
$message2,
$contactform_header2["sender_email"],
$contactform_header2["recipient_email"],
$contactform_header2["sender_name"],
$contactform_header2["recipient_name"],
FALSE,
$file,
"",
"",
0,
"",
""
)
) {
mail_send();
unset($file);
clearstatcache();
$success = true;
$requestmassage .= $GLOBALS['tc']['contactform_success'];
foreach ($_POST as $key => $value) {
unset($_POST[$key]);
}
} else {
$error = TRUE;
$requestmassage .= $translation->get('not_send2');
}
}
}
if ($GLOBAL["ws_bestell_result"] == true) {
$query = "SELECT main_contact.email FROM main_contact JOIN main_contact_department ON main_contact.id = main_contact_department.main_contact_id AND main_role_id = '3' AND main_mandant_id = " . $GLOBALS["main_contact"]["current_mandant_id"];
$result = @mysqli_query($GLOBALS['mysql_con'], $query);
while ($email = @mysqli_fetch_array($result)) {
$contactform_header["recipient_email"] .= "; " . $email["email"];
}
}
$bccEmails = [];
$sender_id = (int) $GLOBALS['main_contact']['id'];
$sender_mandant_id = (int) $GLOBALS['main_contact']['current_mandant_id'];
$responsibleString = $contactform_header['responsible_person'] ?? '';
$responsibleIds = array_filter(array_map('intval', explode(',', $responsibleString)));
if (!empty($responsibleIds) && $sender_mandant_id) {
foreach ($responsibleIds as $pid) {
$pid = (int) $pid;
$check = mysqli_query($GLOBALS['mysql_con'], "
SELECT 1 FROM main_contact_department
WHERE main_contact_id = $pid
AND main_mandant_id = $sender_mandant_id
AND active = 1
LIMIT 1
");
if (mysqli_num_rows($check)) {
$emailRes = mysqli_query($GLOBALS['mysql_con'], "
SELECT email FROM main_contact
WHERE id = $pid AND email != ''
LIMIT 1
");
if ($emailRow = mysqli_fetch_assoc($emailRes)) {
$bccEmails[] = $emailRow['email'];
}
}
}
}
// Add mandant leaders to BCC if mandant_leader_in_cc is enabled
if ((int)($contactform_header["mandant_leader_in_cc"] ?? 0) === 1 && $sender_mandant_id > 0) {
$leadersRes = mysqli_query($GLOBALS['mysql_con'],
"SELECT mc.email FROM main_mandant_leader mml
INNER JOIN main_contact mc ON mc.id = mml.main_contact_id
WHERE mml.main_mandant_id = " . $sender_mandant_id . "
AND mc.active = 1 AND mc.email != ''
ORDER BY mml.sorting ASC"
);
while ($leader = mysqli_fetch_assoc($leadersRes)) {
$bccEmails[] = $leader['email'];
}
}
$bccString = implode(',', array_unique($bccEmails));
$formName = $contactform_header['description'] ?? '—';
$applicantName = $GLOBALS['main_contact']['name'] ?? 'Unbekannt';
$mandantName = '';
$mid = (int) $GLOBALS['main_contact']['current_mandant_id'];
if ($mid) {
$row = mysqli_fetch_assoc(
mysqli_query(
$GLOBALS['mysql_con'],
"SELECT description FROM main_mandant WHERE id = $mid LIMIT 1"
)
);
$mandantName = $row['description'] ?: 'ID ' . $mid;
}
$currentDt = date('d.m.Y H:i');
$formName = htmlspecialchars($contactform_header['description'] ?? '—', ENT_QUOTES);
$applicant = htmlspecialchars($GLOBALS['main_contact']['name'] ?? 'Unbekannt', ENT_QUOTES);
$mandant = '';
$mid = (int) $GLOBALS['main_contact']['current_mandant_id'];
if ($mid) {
$row = mysqli_fetch_assoc(
mysqli_query(
$GLOBALS['mysql_con'],
"SELECT description FROM main_mandant WHERE id = $mid LIMIT 1"
)
);
$mandant = htmlspecialchars($row['description'] ?: 'ID ' . $mid, ENT_QUOTES);
}
$currDt = date('d.m.Y H:i');
$metaHeader = "
<h2 style='margin-top:0;'>Neue Formular-Anfrage</h2>
<p style='margin:0 0 0 0;'><strong>Formular:</strong> $formName</p>
<p style='margin:0 0 0 0;'><strong>Erstellt von:</strong> $applicant</p>
<p style='margin:0 0 0 0;'><strong>Mandant:</strong> $mandant</p>
<p style='margin:0 0 0 0;'><strong>Datum:</strong> $currDt</p>
";
$message = $metaHeader . trim($message);
// fa wenn betreff ist leer
// $contactform_header["subject"] = trim((string)$contactform_header["subject"]);
// if ($contactform_header["subject"] === '') {
// $contactform_header["subject"] = 'Kontaktformular';
// }
if (
mail_create(
$contactform_header["subject"],
$message,
$contactform_header["sender_email"],
$contactform_header["recipient_email"],
$contactform_header["sender_name"],
$contactform_header["recipient_name"],
FALSE,
$file,
$bccString,
"",
0,
"",
$spid
)
) {
mail_send();
unset($file);
clearstatcache();
$success = true;
$requestmassage .= $GLOBALS['tc']['contactform_success'];
foreach ($_POST as $key => $value) {
unset($_POST[$key]);
}
} else {
$error = TRUE;
$requestmassage .= $translation->get('not_send3');
}
} else {
$error = TRUE;
$requestmassage .= $GLOBALS['tc']['mandatory_fields_error'];
if ($filetypeError === TRUE) {
$requestmassage .= $GLOBALS['tc']['contactform_error_php'];
}
}
$mail_query = mysqli_query($GLOBALS['mysql_con'], "SELECT id FROM main_mail_log ORDER BY id DESC LIMIT 1");
$mail_row = mysqli_fetch_assoc($mail_query);
$mail_id = $mail_row['id'] ?? 0;
foreach ($submission_data as $entry) {
$query_entry = "INSERT INTO contactform_entries (mail_id, line_id, value)
VALUES (
$mail_id,
" . intval($entry['field_id']) . ",
'" . mysqli_real_escape_string($GLOBALS['mysql_con'], $entry['value']) . "'
)";
mysqli_query($GLOBALS['mysql_con'], $query_entry);
}
if ($error || $success) {
if ($success) {
get_requestbox($requestmassage, "", "success");
} else {
get_requestbox($requestmassage, "");
}
}
}
// Helper-Funktion zur Berechtigungsprüfung
function require_permission($permissionCode)
{
if (
get_permission_state(
$permissionCode,
$GLOBALS['main_contact']['master_mandant_id'],
$GLOBALS['main_contact']['id']
) != 1
) {
echo "Sie haben nicht die notwendigen Berechtigungen, um diese Seite zu sehen.";
exit;
}
}
// Prüft, ob der User voller Wiki-Redakteur ist (r-wiki)
function is_wiki_redakteur(): bool
{
return get_permission_state('r-wiki', $GLOBALS['main_contact']['master_mandant_id'], $GLOBALS['main_contact']['id']) == 1;
}
// Prüft, ob der User Betriebsrat-Wiki-Recht hat (r-wiki-br)
function is_wiki_betriebsrat(): bool
{
return get_permission_state('r-wiki-br', $GLOBALS['main_contact']['master_mandant_id'], $GLOBALS['main_contact']['id']) == 1;
}
// Prüft, ob der User irgendeins der Wiki-Bearbeitungsrechte hat
function has_wiki_edit_permission(): bool
{
return is_wiki_redakteur() || is_wiki_betriebsrat();
}
function require_wiki_edit_permission(): void
{
if (!has_wiki_edit_permission()) {
echo "Sie haben nicht die notwendigen Berechtigungen, um diese Seite zu sehen.";
exit;
}
}
// Gibt alle Kategorie-IDs zurück, auf die Betriebsrat Zugriff hat:
// direkt betriebsrat_editable=1 sowie alle ihre Nachfahren im Baum (BFS nach unten).
function get_all_betriebsrat_accessible_category_ids(): array
{
$seeds = [];
$res = mysqli_query($GLOBALS['mysql_con'],
"SELECT id FROM knowledgecenter_categories_update WHERE betriebsrat_editable = 1");
while ($row = mysqli_fetch_assoc($res)) {
$seeds[] = (int)$row['id'];
}
if (empty($seeds)) {
return [];
}
$visited = [];
$queue = $seeds;
while (!empty($queue)) {
$current = array_shift($queue);
if (isset($visited[$current])) {
continue;
}
$visited[$current] = true;
$cRes = mysqli_query($GLOBALS['mysql_con'],
"SELECT child_category_id FROM knowledgecenter_category_links WHERE parent_category_id = $current");
while ($cRow = mysqli_fetch_assoc($cRes)) {
$cid = (int)$cRow['child_category_id'];
if (!isset($visited[$cid])) {
$queue[] = $cid;
}
}
}
return array_keys($visited);
}
// Prüft ob eine Kategorie (oder irgendein Vorfahre über knowledgecenter_category_links)
// betriebsrat_editable=1 hat. Läuft den Baum nach oben durch.
function is_category_betriebsrat_editable(int $categoryId): bool
{
$visited = [];
$queue = [$categoryId];
while (!empty($queue)) {
$current = array_shift($queue);
if (isset($visited[$current])) {
continue;
}
$visited[$current] = true;
$res = mysqli_query($GLOBALS['mysql_con'],
"SELECT betriebsrat_editable FROM knowledgecenter_categories_update WHERE id = $current LIMIT 1");
$row = mysqli_fetch_assoc($res);
if ($row && (int)$row['betriebsrat_editable'] === 1) {
return true;
}
$pRes = mysqli_query($GLOBALS['mysql_con'],
"SELECT parent_category_id FROM knowledgecenter_category_links WHERE child_category_id = $current");
while ($pRow = mysqli_fetch_assoc($pRes)) {
$pid = (int)$pRow['parent_category_id'];
if (!isset($visited[$pid])) {
$queue[] = $pid;
}
}
}
return false;
}
// Switch-Case für die verschiedenen Aktionen
$action = $_GET["action"] ?? "List";
switch ($action) {
case "Installation":
require_permission('r-wiki');
require_once(__DIR__ . '/../Installation/Installation.php');
break;
case "Categories":
// Kategorieverwaltung nur für vollständige Redakteure
if (isset($_GET['detail'])) {
require_permission('r-wiki');
require_once(__DIR__ . '/../Views/categories_cardform.php');
} else {
require_permission('r-wiki');
require_once(__DIR__ . '/../Views/categories_listform.php');
}
break;
case "PostList":
// Betriebsrat darf die Post-Liste sehen (gefiltert auf seine Kategorien)
require_wiki_edit_permission();
require_once(__DIR__ . '/../Views/post_listform.php');
break;
case "Post":
require_once(__DIR__ . '/../Views/post_cardform.php');
break;
case "Import":
require_permission('r-wiki');
require_once(__DIR__ . '/../Import/Import.php');
break;
case "NewPost":
// Betriebsrat darf neue Posts erstellen (nur in freigegebenen Kategorien)
require_wiki_edit_permission();
$_GET['new'] = 1;
require_once(__DIR__ . '/../Views/post_cardform.php');
break;
case "List":
default:
require_once(__DIR__ . '/../Views/categories_posts_listform.php');
break;
}
require_once(__DIR__ . '/../Script/Script.php');
require_once(__DIR__ . '/../CSS/CSS.php');
?>