<?php
/* ToDo: Entfernen des headers */
header('Access-Control-Allow-Origin: *');
// unset( $_POST[ 'uploadFile' ] );
// die ( );

if (!isset($_POST['request']) || !isset($_POST['userId']) || !isset($_POST['dataSet']) || !isset($_POST['prefix']))
{
	die('Wrong parameters');
}

$pathRoot = dirname(dirname(__DIR__)) . '/';
include_once($pathRoot . '.config/config_global.php');
include_once(PATH_FNC . 'fnc_webservices.php');

/* Aufbereiten der Tabellen - Daten */
$dataSet = explode('_', $_POST['dataSet']);
$table = (is_numeric(end($dataSet)) || end($dataSet) === '')
	? implode('_', explode('_', $_POST['dataSet'], -1))
	: $_POST['dataSet'];
$table = ($table === 'keyvisual')
	? 'content_image'
	: $table;
if (strpos($table, 'navi_') !== false)
{
	$table = 'navi';
}
$id = (is_numeric(end($dataSet)))
	? end($dataSet)
	: null;

$data = array();
$result = false;

/* Daten abholen */
if ($_POST['request'] === 'getData')
{
	if ($table === 'navi')
	{
		$result = $db->query('SELECT * FROM ' . TBL_RIGHTS . ' WHERE userId = ' . $_POST['userId'] . ' AND rightsPrefix = "' . $_POST['prefix'] . '";');

		if ($result->num_rows !== 0)
		{
			$rights = $result->fetch_assoc();
			$result = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $table . ' ORDER BY ' . $_POST['prefix'] . '_navStart ASC, ' . $_POST['prefix'] . '_navSort ASC;');
			$arr_rights = explode(';', $rights['rights']);

			while ($fetch_data = $result->fetch_assoc())
			{
				$fetch_data[$_POST['prefix'] . '_navEditable'] = 'false';

				if ($rights['rightsType'] === 'ALL' || ($rights['rightsType'] === 'DEF' && (in_array($_POST['prefix'] . '_' . $fetch_data[$_POST['prefix'] . '_navId'], $arr_rights) || in_array($_POST['prefix'] . '_' . $fetch_data[$_POST['prefix'] . '_navStart'], $arr_rights))))
				{
					if (!in_array($_POST['prefix'] . '_' . $fetch_data[$_POST['prefix'] . '_navId'], $arr_rights))
					{
						$arr_rights[] = $_POST['prefix'] . '_' . $fetch_data[$_POST['prefix'] . '_navId'];
					}
					$fetch_data[$_POST['prefix'] . '_navEditable'] = 'true';
				}
				elseif ($rights['rightsType'] === 'DEF' && (in_array($fetch_data[$_POST['prefix'] . '_navId'], $arr_rights) || in_array($fetch_data[$_POST['prefix'] . '_navStart'], $arr_rights)))
				{
					if (!in_array($fetch_data[$_POST['prefix'] . '_navId'], $arr_rights))
					{
						$arr_rights[] = $fetch_data[$_POST['prefix'] . '_navId'];
					}
					$fetch_data[$_POST['prefix'] . '_navEditable'] = 'true';
				}
				$data['navigation']['navStart_' . $fetch_data[$_POST['prefix'] . '_navStart']]['navId_' . $fetch_data[$_POST['prefix'] . '_navId']] = $fetch_data;
			}
			$data['navPath'] = explode(' ', fnc_getNavPathArray($_POST['prefix'], $_POST['navId']));
		}
		else
		{
			$data = 'ERROR FETCHING USER RIGHTS';
		}
	}
	else
	{
		$result = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE id = ' . $id . ';');
		$fetch_data = $result->fetch_assoc();
		$data = $fetch_data;
	}

	echo json_encode($data, JSON_UNESCAPED_UNICODE);
}
else if ($_POST['request'] === 'updateData')
{
	$error = false;

	if ($table === 'navi')
	{

		switch ($_POST['formAction'])
		{
			case 'renameNavPoint' :
				$result = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navName = "' . $_POST['navName'] . '" WHERE ' . $_POST['prefix'] . '_navId = ' . $_POST['navId'] . ' LIMIT 1;');
				break;

			case 'updateActive' :
				$result = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navActive = "' . $_POST['navActive'] . '" WHERE ' . $_POST['prefix'] . '_navId = ' . $_POST['navId'] . ' LIMIT 1;');
				break;

			case 'sortNavPoint' :
				$sort = 1;
				$newSort = json_decode($_POST['newSort']);

				foreach ($newSort as $sortPoint)
				{
					$navPointArray = explode('_', $sortPoint);
					$navId = $navPointArray[1];
					$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navSort = "' . $sort . '" WHERE ' . $_POST['prefix'] . '_navId = ' . $navId . ' LIMIT 1;');
					++$sort;
				}

				$result = true;
				break;

			case 'moveNavPoint' :
				$result = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navStart = ' . $_POST['navStart'] . ' WHERE ' . $_POST['prefix'] . '_navId = ' . $_POST['navId'] . ' LIMIT 1;');
				break;

			default :
				var_dump($_POST);
				break;

		}

		if (!$result)
		{
			$error = true;
		}
	}
	else
	{
		$columns = $db->query('SHOW COLUMNS FROM ' . $_POST['prefix'] . '_' . $table . ';');
		$fieldNames = array();

		while ($column = $columns->fetch_assoc())
		{
			$fieldNames[] = $column['Field'];
		}

		foreach ($_POST as $key => $value)
		{
			if (in_array($key, $fieldNames))
			{
				$data[] = $key . ' = "' . $db->real_escape_string($value) . '"';
			}
		}

		/* Behandlung Keyvisual und Content-Image */
		if ($table === 'content_image')
		{
			if (!is_dir(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId']))
			{
				mkdir(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'], 0755);
			}

			if (isset ($_POST['uploadFile']) && !empty ($_POST['uploadFile']))
			{
				$old = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE id = ' . $id . ';');
				$old_data = $old->fetch_assoc();

				if (!isset ($_POST['formAction']) || (isset ($_POST['formAction']) && $_POST['formAction'] !== 'appendImage'))
				{
					$file_path = WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $old_data['imgName'];

					/* Alte Bilddaten löschen */
					unlink($file_path . '.' . $old_data['imgExtension']);
					unlink($file_path . '_orig.' . $old_data['imgExtension']);
					unlink($file_path . '_thumb.' . $old_data['imgExtension']);
				}

				/* Bilddaten auslesen */
				$imageData = explode(',', $_POST['uploadFile']);

				/* Bilddaten dekodieren */
				$mimetype = str_replace(array('data:', ';base64'), '', $imageData[0]);
				$encodedData = str_replace(' ', '+', $imageData[1]);
				$decodedData = base64_decode($encodedData);

				/* Bildnamen und Erweiterung generieren */
				$keys = (array_keys($vC['mimetypes'], $mimetype));
				$extension = $keys[0];
				$file_name = fnc_buildUniqueFileName($_POST['prefix'], $_POST['navId'], $_POST['imgName'], $extension);

				/* Originales Bild speichern */
				$file_name_temp = substr($file_name, 0, strrpos($file_name, '.')) . '_temp' . substr($file_name, strrpos($file_name, '.'));
				$file_name_orig = substr($file_name, 0, strrpos($file_name, '.')) . '_orig' . substr($file_name, strrpos($file_name, '.'));

				file_put_contents(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name_temp, $decodedData);
				fnc_checkOrigResize(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/', $file_name_orig, $file_name_temp, $extension, ${$_POST['prefix']}['dimOrig']);

				if (isset ($_POST['formAction']) && $_POST['formAction'] === 'appendImage')
				{
					/* Werte für Datenbank aktualisieren */
					foreach ($data as $key => $value)
					{
						if (strpos($value, 'imgExtension') !== false)
						{
							$data[$key] = 'imgExtension = "' . $db->real_escape_string($extension) . '"';
						}
						else if (strpos($value, 'imgName') !== false)
						{
							$data[$key] = 'imgName = "' . $db->real_escape_string(str_replace('.' . $extension, '', $file_name)) . '"';
						}
					}

					$new = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . $table . ' SET ' . implode(' , ', $data));
					$new_id = $db->insert_id;

					unset ($data);

					if ($old_data['sliderContent'] === '')
					{
						$slider = array($new_id);
					}
					else
					{
						$slider = explode(';', $old_data['sliderContent']);
						$slider[] = $new_id;
					}

					$data = array();
					$data[] = 'sliderContent = "' . $db->real_escape_string(implode(';', $slider)) . '"';
					$data[] = 'hasSlider = "Y"';
				}
			}
			else
			{
				if (isset ($_POST['formAction']) && $_POST['formAction'] === 'updateSort')
				{
					$db->query('UPDATE ' . $_POST['prefix'] . '_' . TBL_NAVI . ' SET ' . $_POST['prefix'] . '_keyvisual = ' . $id . ' WHERE ' . $_POST['prefix'] . '_navId = ' . $_POST['navId'] . ' LIMIT 1;');
				}
				else
				{
					/* Altes Bild umbenennen und neue Koordinaten speichern */
					$img = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE id = ' . $id . ';');
					$img_data = $img->fetch_assoc();

					$extension = $img_data['imgExtension'];
					$old_name = $img_data['imgName'] . '.' . $extension;
					$old_name_orig = substr($old_name, 0, strrpos($old_name, '.')) . '_orig' . substr($old_name, strrpos($old_name, '.'));
					$old_name_thumb = substr($old_name, 0, strrpos($old_name, '.')) . '_thumb' . substr($old_name, strrpos($old_name, '.'));

					$img_name = $_POST['imgName'];
					$img_name = explode('_', $img_name);
					foreach ($img_name as $key => $value)
					{
						if (is_numeric($value))
						{
							unset ($img_name[$key]);
						}
					}
					$img_name = implode('_', $img_name);

					if ($_POST['imgName'] . '.' . $_POST['imgExtension'] !== $old_name)
					{
						$file_name = fnc_buildUniqueFileName($_POST['prefix'], $_POST['navId'], $img_name, $extension);
						$file_name_orig = substr($file_name, 0, strrpos($file_name, '.')) . '_orig' . substr($file_name, strrpos($file_name, '.'));
						$file_name_thumb = substr($file_name, 0, strrpos($file_name, '.')) . '_thumb' . substr($file_name, strrpos($file_name, '.'));

						rename(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $old_name_thumb, WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name_thumb);
						rename(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $old_name_orig, WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name_orig);
						rename(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $old_name, WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name);
					}
					else
					{
						$file_name = $old_name;
						$file_name_orig = $old_name_orig;
						$file_name_thumb = $old_name_thumb;
					}
				}
			}

			if (!isset ($_POST['formAction']) || (isset ($_POST['formAction']) && $_POST['formAction'] !== 'updateSort'))
			{
				$dataSet = str_replace('content_', '', $_POST['dataSet']);

				/* Bilddaten aus Editor generieren */
				if (strpos($dataSet, 'image') === 0)
				{
					${$_POST['prefix']}['dim' . strtoupper(substr($dataSet, 0, 1)) . substr($dataSet, 1, strrpos($dataSet, '_') - 1)]['height'] = ${$_POST['prefix']}['dim' . strtoupper(substr($dataSet, 0, 1)) . substr($dataSet, 1, strrpos($dataSet, '_') - 1)]['width'] * $_POST['previewHeight'] / $_POST['previewWidth'];
				}
				$img_created = fnc_buildImage(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/', $file_name_orig, $extension, ${$_POST['prefix']}['dim' . strtoupper(substr($dataSet, 0, 1)) . substr($dataSet, 1, strrpos($dataSet, '_') - 1)], $_POST);

				/* Thumbnail aus generiertem Bild erzeugen */
				if (!is_null(${$_POST['prefix']}[substr($dataSet, 0, strrpos($dataSet, '_')) . 'Thumb']))
				{
					if (strpos($dataSet, 'image') === 0)
					{
						${$_POST['prefix']}[substr($dataSet, 0, strrpos($dataSet, '_')) . 'Thumb']['height'] = ${$_POST['prefix']}[substr($dataSet, 0, strrpos($dataSet, '_')) . 'Thumb']['width'] * $_POST['previewHeight'] / $_POST['previewWidth'];
					}
					$thumb = fnc_buildThumbnail(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/', $file_name, $extension, ${$_POST['prefix']}[substr($dataSet, 0, strrpos($dataSet, '_')) . 'Thumb']);
				}

				/* Werte für Datenbank aktualisieren */
				foreach ($data as $key => $value)
				{
					if (strpos($value, 'imgExtension') !== false)
					{
						$data[$key] = 'imgExtension = "' . $db->real_escape_string($extension) . '"';
					}
					else if (strpos($value, 'imgName') !== false)
					{
						$data[$key] = 'imgName = "' . $db->real_escape_string(str_replace('.' . $extension, '', $file_name)) . '"';
					}
				}

				if (!$img_created || !$thumb)
				{
					$error = true;
				}
			}
		}

		if (!$error)
		{
			/* Daten in Tabelle schreiben */
			$dataString = implode(' , ', $data);

			if ($dataString != '')
			{
				$result = ($table === 'content')
					? $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $dataString . ' WHERE siteId = ' . $id . ';')
					: $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $dataString . ' WHERE id = ' . $id . ';');

				if (!$result)
				{
					$error = true;
				}
			}
			else
			{
				$error = true;
			}
		}
	}

	if ($error)
	{
		echo 'ERROR';
	}
	else
	{
		echo 'SUCCESS';
	}
}
else if ($_POST['request'] === 'insertData')
{
	$error = false;
	if ($table === 'navi')
	{

		switch ($_POST['formAction'])
		{
			case 'addNavPoint' :
				$navis = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE ' . $_POST['prefix'] . '_navStart = "' . $_POST['navStart'] . '" ORDER BY ' . $_POST['prefix'] . '_navSort ASC;');
				$sort = 1;

				while ($navi = $navis->fetch_assoc())
				{
					$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navSort = "' . $sort . '" WHERE ' . $_POST['prefix'] . '_navId = "' . $navi[$_POST['prefix'] . '_navId'] . '" LIMIT 1;') || $error = true;

					if ($error)
					{
						break;
					}
					if ($navi[$_POST['prefix'] . '_navId'] == $_POST['navId'])
					{
						++$sort;
						$special = ($_POST['new_navType'] === 'content')
							? 'N'
							: 'Y';
						$navLink = fnc_buildUniqueLinkName($_POST['prefix'], $_POST['navStart'], $_POST['new_navName']);

						$insert = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . $table . ' ( ' . $_POST['prefix'] . '_navId , ' . $_POST['prefix'] . '_navStart , ' . $_POST['prefix'] . '_navName , ' . $_POST['prefix'] . '_navTarget , ' . $_POST['prefix'] . '_navLink , ' . $_POST['prefix'] . '_navActive , ' . $_POST['prefix'] . '_navSort , ' . $_POST['prefix'] . '_specialSite , ' . $_POST['prefix'] . '_specialType ) VALUES ( NULL , "' . $_POST['navStart'] . '" , "' . $_POST['new_navName'] . '" , "" , "' . $navLink . '" , "Y" , "' . $sort . '" , "' . $special . '" , "' . $_POST['new_navType'] . '" );') || $error = true;
						$new_navId = $db->insert_id;
						$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navTarget = "index.php?siteId=' . $_POST['siteId'] . '&navId=' . $new_navId . '" WHERE ' . $_POST['prefix'] . '_navId = "' . $new_navId . '" LIMIT 1;') || $error = true;

						if ($error)
						{
							break;
						}

						if ($_POST['new_navType'] !== 'uebersicht')
						{

							if ($_POST['new_navType'] === 'content')
							{
								$headline = $db->query('INSERT INTO ' . $_POST['prefix'] . '_content_headline ( id , content ) VALUES ( null , "Neue Überschrift" );');
								$h_id = $db->insert_id;
								$test = $db->query('INSERT INTO ' . $_POST['prefix'] . '_content_text ( id , content ) VALUES ( null , "Neuer Standardtext" );');
								$t_id = $db->insert_id;
								$site = $db->query('INSERT INTO ' . $_POST['prefix'] . '_content ( id , siteId , siteContents ) VALUES ( null , "' . $new_navId . '" , "headline_' . $h_id . ';text_' . $t_id . '" );');
							}
							else
							{
								$site = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . $_POST['new_navType'] . ' ( id , siteId ) VALUES ( null , "' . $new_navId . '" );');
							}
						}

					}
					++$sort;
				}

				break;

			case 'addSubNav' :
				$navis = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE ' . $_POST['prefix'] . '_navStart = ' . $_POST['navId'] . ' ORDER BY ' . $_POST['prefix'] . '_navSort ASC;');
				$sort = 1;

				$special = ($_POST['new_subnavType'] === 'content') ? 'N' : 'Y';
				$navLink = fnc_buildUniqueLinkName($_POST['prefix'], $_POST['navId'], $_POST['new_subnavName']);

				$insert = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . $table . ' ( ' . $_POST['prefix'] . '_navId , ' . $_POST['prefix'] . '_navStart , ' . $_POST['prefix'] . '_navName , ' . $_POST['prefix'] . '_navTarget , ' . $_POST['prefix'] . '_navLink , ' . $_POST['prefix'] . '_navActive , ' . $_POST['prefix'] . '_navSort , ' . $_POST['prefix'] . '_specialSite , ' . $_POST['prefix'] . '_specialType ) VALUES ( NULL , "' . $_POST['navId'] . '" , "' . $_POST['new_subnavName'] . '" , "" , "' . $navLink . '" , "Y" , "' . $sort . '" , "' . $special . '" , "' . $_POST['new_subnavType'] . '" );') || $error = true;
				$new_navId = $db->insert_id;
				$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navTarget = "index.php?siteId=' . $_POST['siteId'] . '&navId=' . $new_navId . '" WHERE ' . $_POST['prefix'] . '_navId = "' . $new_navId . '" LIMIT 1;') || $error = true;

				if ($error)
				{
					break;
				}

				if ($_POST['new_subnavType'] !== 'uebersicht')
				{

					if ($_POST['new_subnavType'] === 'content')
					{
						$headline = $db->query('INSERT INTO ' . $_POST['prefix'] . '_content_headline ( id , content ) VALUES ( null , "Neue Überschrift" );');
						$h_id = $db->insert_id;
						$test = $db->query('INSERT INTO ' . $_POST['prefix'] . '_content_text ( id , content ) VALUES ( null , "Neuer Standardtext" );');
						$t_id = $db->insert_id;
						$site = $db->query('INSERT INTO ' . $_POST['prefix'] . '_content ( id , siteId , siteContents ) VALUES ( null , "' . $new_navId . '" , "headline_' . $h_id . ';text_' . $t_id . '" );');
					}
					else
					{
						$site = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . $_POST['new_subnavType'] . ' ( id , siteId ) VALUES ( null , "' . $new_navId . '" );');
					}
				}

				++$sort;

				while ($navi = $navis->fetch_assoc())
				{
					$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $table . ' SET ' . $_POST['prefix'] . '_navSort = "' . $sort . '" WHERE ' . $_POST['prefix'] . '_navId = "' . $navi[$_POST['prefix'] . '_navId'] . '" LIMIT 1;') || $error = true;

					if ($error)
					{
						break;
					}
					++$sort;
				}

				break;

			default :
				var_dump($_POST);
				break;

		}

		if (!$error)
		{
			echo 'SUCCESS';
		}
		else
		{
			echo 'ERROR';
		}
	}
	else
	{
		$columns = $db->query('SHOW COLUMNS FROM ' . $_POST['prefix'] . '_' . $table . ';');
		$fieldNames = array();
		while ($column = $columns->fetch_assoc())
		{
			$fieldNames[] = $column['Field'];
		}

		foreach ($_POST as $key => $value)
		{
			if (in_array($key, $fieldNames))
			{
				$data[$key] = $db->real_escape_string($value);
			}
		}

		if ($table === 'content_image')
		{
			if (!is_dir(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId']))
			{
				mkdir(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'], 0755);
			}

			/* Bilddaten auslesen */
			$imageData = explode(',', $_POST['uploadFile']);

			/* Bilddaten dekodieren */
			$mimetype = str_replace(array('data:', ';base64'), '', $imageData[0]);
			$encodedData = str_replace(' ', '+', $imageData[1]);
			$decodedData = base64_decode($encodedData);

			/* Bildnamen und Erweiterung generieren */
			$keys = (array_keys($vC['mimetypes'], $mimetype));
			$extension = $keys[0];
			$file_name = fnc_buildUniqueFileName($_POST['prefix'], $_POST['navId'], $_POST['imgName'], $extension);

			/* Originales Bild speichern */
			$file_name_orig = substr($file_name, 0, strrpos($file_name, '.')) . '_orig' . substr($file_name, strrpos($file_name, '.'));
			file_put_contents(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name_orig, $decodedData);

			/* Bilddaten aus Editor generieren */
			$img_created = fnc_buildImage(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/', $file_name_orig, $extension, ${$_POST['prefix']}['dim' . strtoupper(substr($_POST['dataSet'], 0, 1)) . substr($_POST['dataSet'], 1)], $_POST);

			/* Thumbnail aus generiertem Bild erzeugen */
			if (!is_null(${$_POST['prefix']}[$_POST['dataSet'] . 'Thumb']))
			{
				$thumb = fnc_buildThumbnail(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/', $file_name, $extension, ${$_POST['prefix']}[$_POST['dataSet'] . 'Thumb']);
			}

			/* Werte für Datenbank aktualisieren */
			$data['imgExtension'] = $db->real_escape_string($extension);
			$data['imgName'] = $db->real_escape_string(str_replace('.' . $extension, '', $file_name));

			if (!$img_created || !$thumb)
			{
				$error = true;
			}

		}

		else if ($table === 'content_textimage')
		{
			if (!is_dir(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId']))
			{
				mkdir(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'], 0755);
			}

			/* Bildnamen und Erweiterung generieren */
			$extension = 'jpg';
			$file_name = fnc_buildUniqueFileName($_POST['prefix'], $_POST['navId'], 'sample_image', $extension);

			/* Originales Bild speichern */
			$file_name_orig = substr($file_name, 0, strrpos($file_name, '.')) . '_orig' . substr($file_name, strrpos($file_name, '.'));
			copy(WEBSERVICE_MED . $_POST['prefix'] . '/sample_image.jpg', WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name_orig);
			copy(WEBSERVICE_MED . $_POST['prefix'] . '/sample_image.jpg', WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/' . $file_name);

			/* Thumbnail aus generiertem Bild erzeugen */
			if (!is_null(${$_POST['prefix']}['imageThumb']))
			{
				$thumb = fnc_buildThumbnail(WEBSERVICE_MED . $_POST['prefix'] . '/' . $_POST['navId'] . '/', $file_name, $extension, ${$_POST['prefix']}['imageThumb']);
			}

			if (!$thumb)
			{
				$error = true;
			}

			$img_extension = $db->real_escape_string($extension);
			$img_name = $db->real_escape_string(str_replace('.' . $extension, '', $file_name));
			$img_title = $db->real_escape_string('Sample Image');

			$image = $db->query('INSERT INTO  ' . $_POST['prefix'] . '_' . TBL_IMAGE . ' (imgName, imgExtension, imgOrigname, imgTitle, previewWidth, previewHeight) VALUES ("' . $img_name . '", "' . $img_extension . '", "' . $img_name . '.' . $img_extension . '", "' . $img_title . '", "' . ${$_POST['prefix']}['dimImage']['width'] . '", "' . ${$_POST['prefix']}['dimImage']['width'] * 4 / 3 . '");');
			$image_id = $db->insert_id;

			$text = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . TBL_TEXT . ' VALUES (NULL, "' . $_POST['content'] . '" );');
			$text_id = $db->insert_id;

			$data['content_text_id'] = $text_id;
			$data['content_image_id'] = $image_id;
		}

		$keys = array();
		$values = array();
		foreach ($data as $key => $value)
		{
			$keys[] = $key;
			$values[] = '"' . $value . '"';
		}

		/* Daten in Tabelle schreiben */
		if (!empty ($data) && $error === false)
		{
			$result = $db->query('INSERT INTO ' . $_POST['prefix'] . '_' . $table . ' ( ' . implode(' , ', $keys) . ' ) VALUES ( ' . implode(' , ', $values) . ' );');

			if ($result !== false)
			{
				if ($_POST['dataSet'] === 'keyvisual')
				{
					$insert = $db->insert_id;
					$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . TBL_NAVI . ' SET ' . $_POST['prefix'] . '_keyvisual = "' . $insert . '" WHERE ' . $_POST['prefix'] . '_navId = "' . $_POST['navId'] . '" LIMIT 1;');

					if ($update)
					{
						$error = false;
					}
					else
					{
						$error = true;
					}
				}
				elseif ($table === 'content_text' || $table === 'content_subline' || $table === 'content_textimage')
				{
					$insert = $db->insert_id;
					$siteContents = $_POST['order'];

					foreach ($siteContents as $key => $value)
					{
						$content = explode('_', $value);
						$siteContents[$key] = str_replace('content_', '', $value);
						if (!is_numeric(end($content)))
						{
							$siteContents[$key] .= $insert;
						}
					}

					$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . TBL_CONTENT . ' SET siteContents = "' . implode(';', $siteContents) . '" WHERE siteId = "' . $_POST['navId'] . '" LIMIT 1;');

					if ($update)
					{
						echo json_encode($insert);
						die();
					}
					else
					{
						$error = true;
					}

				}
				elseif (isset ($_POST['formAction']) && $_POST['formAction'] === 'appendContent')
				{
					/**
					 * TODO: Eventuell unnötig
					 */
					$newId = $table . '_' . $db->insert_id;
					$mainSet = explode('_', $_POST['mainContent']);

					$oldContent = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . $mainSet[0] . ' WHERE id = "' . $mainSet[1] . '";');
					$content = $oldContent->fetch_assoc();
					$siteContent = ($content['siteContents'] === '') ? $newId : $content['siteContents'] . ';' . $newId;
					$update = $db->query('UPDATE ' . $_POST['prefix'] . '_' . $mainSet[0] . ' SET siteContents = "' . $siteContent . '" WHERE id = "' . $mainSet[1] . '" LIMIT 1;');
					if ($update)
					{
						json_encode($update);
						die();
					}
					else
					{
						$error = true;
					}
				}
				else
				{
					$error = false;
				}
			}
			else
			{
				$error = true;
			}
		}

		if ($error === false)
		{
			echo 'SUCCESS';
		}
		else
		{
			echo 'ERROR';
		}
	}
}
else if ($_POST['request'] === 'deleteData')
{
	$error = false;
	$result = ($table === 'content')
		? $db->query('DELETE FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE siteId = "' . $id . '" LIMIT 1;')
		: $db->query('DELETE FROM ' . $_POST['prefix'] . '_' . $table . ' WHERE id = "' . $id . '" LIMIT 1;');

	if ($result && strpos($table, 'content_') !== false)
	{
		$content_part = str_replace('content_', '', $_POST['dataSet']);
		$content_data = $db->query('SELECT * FROM ' . $_POST['prefix'] . '_' . TBL_CONTENT . ' WHERE siteId = "' . $_POST['navId'] . '";');

		$content = $content_data->fetch_assoc();
		$siteContents = explode(';', $content['siteContents']);
		$content_key = array_keys($siteContents, $content_part);

		if (!empty($content_key))
		{
			unset ($siteContents[$content_key[0]]);
			$db->query('UPDATE ' . $_POST['prefix'] . '_' . TBL_CONTENT . ' SET siteContents = "' . implode(';', $siteContents) . '" WHERE id = "' . $content['id'] . '" LIMIT 1;') || $error = true;
		}
	}

	if (!$error)
	{
		echo 'SUCCESS';
	}
	else
	{
		echo 'ERROR';
	}
}