<?php

function fnc_getNavigationArray($prefix, $onlyActive = true, $navPositions = array(), $namesFromConfig = array())
{
	global $db;
	$return = array();

	$str_filter = (count($navPositions) > 0)
		? '( ' . $prefix . '_navPosition = "' . implode('" OR ' . $prefix . '_navPosition = "', $navPositions) . '" )'
		: '';
	$str_filter .= ($onlyActive)
		? ($str_filter === '')
			? $prefix . '_navActive = "Y"'
			: ' AND ' . $prefix . '_navActive = "Y"'
		: '';
	$str_filter = ($str_filter !== '')
		? ' WHERE ' . $str_filter
		: '';

	$navi = $db->query('SELECT * FROM ' . $prefix . '_' . TBL_NAVI . $str_filter . ' ORDER BY ' . $prefix . '_navStart ASC , ' . $prefix . '_navSort ASC;');

	while ($dat_navi = $navi->fetch_assoc())
	{
		if (!empty($namesFromConfig))
		{
			$dat_navi[$prefix . '_navName'] = $namesFromConfig['site_' . $dat_navi[$prefix . '_navId']];
		}
		$return[$dat_navi[$prefix . '_navStart']][] = $dat_navi;
	}

	return $return;
}

function fnc_getSingleNavigationArrays($prefix, $navArray, $params, $pathWay)
{
	$i = 0;
	$return = array();

	foreach ($params['navLevel'] as $key => $depth)
	{
		if ($params['navDepth'][$key])
		{
			if (isset ($pathWay[$i]) && isset ($navArray[$pathWay[$i]]))
			{
				$return[$key][$pathWay[$i]] = $navArray[$pathWay[$i]];
				++$i;
				while ($i < $depth)
				{
					foreach ($return[$key] as $subArray)
					{
						foreach ($subArray as $navPoint)
						{
							if (isset ($navArray[$navPoint[$prefix . '_navId']]))
							{
								$return[$key][$navPoint[$prefix . '_navId']] = $navArray[$navPoint[$prefix . '_navId']];
							}
						}
					}
					++$i;
				}
			}
			else
			{
				if (!isset ($return[$key]))
				{
					$return[$key] = null;
				}
			}
		}
		else
		{
			/* Nur die aktuelle Unternavigation */
			while ($i < $depth && isset ($pathWay [$i]))
			{
				if (isset ($navArray[$pathWay[$i]]))
				{
					$return[$key][$pathWay[$i]] = $navArray[$pathWay[$i]];
				}
				else
				{
					if (!isset ($return[$key]))
					{
						$return[$key] = null;
					}
				}
				++$i;
			}
		}
	}

	return $return;
}

function fnc_getPortalNavigationArray($prefix, $navArray, $rightsArray)
{
	foreach ($navArray as $navStart => $navLevels)
	{
		if ($navStart > 0)
		{
			if (!in_array($prefix . '_' . $navStart, $rightsArray) && !in_array($navStart, $rightsArray))
			{
				unset ($navArray[$navStart]);
			}
		}
	}
	foreach ($navArray as $key => $navLevels)
	{
		foreach ($navLevels as $subKey => $navPoint)
		{
			if (intval($navPoint[$prefix . '_navId']) > 1 && (!in_array($prefix . '_' . $navPoint[$prefix . '_navId'], $rightsArray)) && !in_array($navPoint[$prefix . '_navId'], $rightsArray))
			{
				unset ($navArray[$key][$subKey]);
			}
		}

	}
	return ($navArray);
}

function fnc_createPathHome($prefix, $navActive)
{
	global $db;

	$navi = $db->query('SELECT * FROM ' . $prefix . '_' . TBL_NAVI . ' WHERE ' . $prefix . '_navId = "' . $navActive . '";');
	$arr_navi = $navi->fetch_assoc();
	if ($arr_navi[$prefix . '_navStart'] !== '0' && !is_null($arr_navi))
	{
		$return = fnc_createPathHome($prefix, $arr_navi[$prefix . '_navStart']);
	}
	else
	{
		$return[] = '0';
	}
	$return[] = $navActive;

	return $return;
}

function fnc_getNavType($prefix, $navActive)
{
	global $db;

	$navi = $db->query('SELECT * FROM ' . $prefix . '_' . TBL_NAVI . ' WHERE ' . $prefix . '_navId = "' . $navActive . '";');
	$navPoint = $navi->fetch_assoc();

	if ($navPoint[$prefix . '_specialSite'] === 'Y')
	{
		return $navPoint[$prefix . '_specialType'];
	}
	else
	{
		return false;
	}
}

function fnc_getUsernameById($userId)
{
	global $db;
	$return = '';

	$user = $db->query('SELECT * FROM ' . TBL_USER . ' WHERE userId = "' . $userId . '";');
	if ($user->num_rows > 0)
	{
		$dat_user = $user->fetch_assoc();
		$return = $dat_user['userLastname'] . ', ' . $dat_user['userFirstname'];
	}

	return $return;
}

function fnc_getTimeByTS($timeStamp)
{
	$time = new DateTime ($timeStamp);

	return $time->format('d.m.Y - H:i:s');
}

function fnc_generatePW($length = 8)
{
	$passWord = '';

	$pool = "qwertzupasdfghkyxcvbnm";
	$pool .= "23456789";
	$pool .= "WERTZUPLKJHGFDSAYXCVBNM";
	$pool .= "!�$%&/()=";

	srand(( double )microtime() * 1000000);

	for ($i = 0; $i < $length; $i++)
	{
		$passWord .= substr($pool, (rand() % (strlen($pool))), 1);
	}

	return $passWord;
}

function fnc_generateUniqueUsername($lastName, $firstName)
{
	global $db;

	$username = mb_strtolower(substr($firstName, 0, 1), 'UTF-8') . mb_strtolower($lastName, 'UTF-8');
	$count = $db->query('SELECT * FROM ' . TBL_USER . ' WHERE userUsername = "' . $username . '" OR userUsername LIKE "' . $username . '_%";');

	if ($count->num_rows !== 0)
	{
		$username .= '_' . $count->num_rows;
	}

	return $username;
}

function fnc_writeLog($entry, $params, $userId)
{
	global $db;
	$db->query('INSERT INTO ' . TBL_LOG . '(logEntry, logParams, logUser) VALUES ("' . $entry . '", "' . implode('::', $params) . '", "' . $userId . '");');
}

function fnc_readLog($entry, $params)
{
	if ($params !== '')
	{
		$arr_params = explode('::', $params);
		foreach ($arr_params as $key => $value)
		{
			$entry = str_replace('%' . $key . '%', $value, $entry);
		}
	}
	return $entry;
}

function fnc_sendEmailToUser($mailId, $userId, $sessionUserId)
{
	global $db;
	global $vC;
	global $lang;

	$result = $db->query('SELECT * FROM ' . TBL_USER . ' WHERE userId = "' . $userId . '" LIMIT 1;');
	$recipient = $result->fetch_assoc();

	$result = $db->query('SELECT * FROM ' . TBL_USER . ' WHERE userId = "' . $sessionUserId . '" LIMIT 1;');
	$sender = $result->fetch_assoc();

	$mailSubj = $lang['mail']['subj'][$mailId];
	$mailBody = $lang['mail']['body'][$mailId];

	foreach ($recipient as $key => $value)
	{
		$mailBody = str_replace('%' . $key . '%', $value, $mailBody);
	}
	foreach ($sender as $key => $value)
	{
		$mailBody = str_replace('%sess_' . $key . '%', $value, $mailBody);
	}

	require_once(PATH_CLS . 'phpmailer/PHPMailerAutoload.php');
	$mail = new PHPMailer;

	if ($vC['portal']['mail']['type'] === 'smtp')
	{
		$mail->isSMTP();
		$mail->Host = $vC['portal']['mail']['smtpHost'];
		$mail->SMTPAuth = $vC['portal']['mail']['smtpAuth'];
		$mail->Username = $vC['portal']['mail']['smtpUser'];
		$mail->Password = $vC['portal']['mail']['smtpPass'];
	}

	$mail->From = $vC['portal']['mail']['from'];
	$mail->FromName = $vC['portal']['mail']['fromName'];
	$mail->ReturnPath = $vC['portal']['mail']['returnPath'];
	$mail->CharSet = $vC['portal']['mail']['charset'];
	$mail->addAddress($recipient['userEmail'], $recipient['userFirstname'] . ' ' . $recipient['userLastname']);
	$mail->isHTML($vC['portal']['mail']['html']);

	$mail->Subject = $mailSubj;
	$mail->Body = $mailBody;

	if (!$mail->send())
	{
		$return = $mail->ErrorInfo;
	}
	else
	{
		$return = 'OK';
	}
	return $return;
}

function fnc_validateEmailAddress($emailAddress)
{
	if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) === false)
	{
		return false;
	}
	return true;
}

function fnc_checkUniqueEmailAddress($emailAddress, $userId = '')
{
	global $db;
	$return = false;

	if ($userId !== '')
	{
		$count = $db->query('SELECT * FROM ' . TBL_USER . ' WHERE userId != "' . $userId . '" AND userEmail = "' . $emailAddress . '";');
	}
	else
	{
		$count = $db->query('SELECT * FROM ' . TBL_USER . ' WHERE userEmail = "' . $emailAddress . '";');
	}
	if ($count->num_rows === 0)
	{
		$return = true;
	}
	return $return;
}

function fnc_getSiteContents($contentParts, $prefix)
{
	global $db;
	$return = array();

	$siteContents = explode(';', $contentParts);
	foreach ($siteContents as $tmp_content)
	{
		if ($tmp_content === '')
		{
			continue;
		}
		$tmp_data = explode('_', $tmp_content);

		$id = end($tmp_data);
		unset ($tmp_data[count($tmp_data) - 1]);
		$table = implode('_', $tmp_data);

		if ($table === '')
		{
			continue;
		}

		if ($table === 'textimage')
		{
			$tmp_content = $db->query('SELECT * , ' . $prefix . '_' . TBL_TEXTIMAGE . '.id AS text_image_id FROM ' . $prefix . '_' . TBL_TEXTIMAGE . ', ' . $prefix . '_' . TBL_TEXT . ', ' . $prefix . '_' . TBL_IMAGE . ' WHERE ' . $prefix . '_' . TBL_TEXTIMAGE . '.content_text_id = ' . $prefix . '_' . TBL_TEXT . '.id AND ' . $prefix . '_' . TBL_TEXTIMAGE . '.content_image_id = ' . $prefix . '_' . TBL_IMAGE . '.id AND ' . $prefix . '_' . TBL_TEXTIMAGE . '.id = ' . $id . ' LIMIT 1;');
		}
		else
		{
			$tmp_content = $db->query('SELECT * FROM ' . $prefix . '_content_' . $table . ' WHERE id = ' . $id . ';');
		}

		if ($tmp_content->num_rows === 0)
		{
			continue;
		}

		$singleContent = $tmp_content->fetch_assoc();
		$singleContent['type'] = $table;
		$return[] = $singleContent;

	}
	return $return;
}