<?php
page_open(array('sess' => 'dedi_Frontend_Session',
                'auth' => 'dedi_Frontend_Auth'));

// Rechte initialisieren
$perm = &new dedi_perms($client, $lang);

// Zeichensatz senden
header('Content-Type: text/html; charset='.$perm->get_lang_charset());

// 404 Fehler
function frontend_errorpage($idcatside='') {
	global $cfg_client, $con_side;

	if ($cfg_client['errorpage'] != '0' && $cfg_client['errorpage'] != $idcatside) {
		$cfg_client['errorpage'] = $con_side[$cfg_client['errorpage']]['link'];
		header ('Location: '.str_replace('&amp;', '&', modrewrite_replace($cfg_client['errorpage'])));
		exit;
	} else {
		header ('Status: 404 Not Found');
		exit;
	}
}
if (!defined('IS_DEDI')) die();
// Aufbau des Arrays $con_tree
$sql = "SELECT B.idcat, B.parent, B.sortindex, C.idcatlang, C.author, C.created, C.lastmodified,
	IF (((C.visible & 0x03) = 0x01) ,'1' ,'0') AS visible,
	IF (((C.visible & 0x04) = 0x00) ,'0' ,'1') AS locked,
         C.idtplconf, C.name, C.description
	FROM ".$dedi_db['cat']." B
         LEFT JOIN ".$dedi_db['cat_lang']." C USING(idcat)
         LEFT JOIN ".$dedi_db['tpl_conf']." D USING(idtplconf)
         LEFT JOIN ".$dedi_db['tpl']." E USING(idtpl)
	WHERE C.idlang = '$lang'
	ORDER BY parent, sortindex";
$db->query($sql, 1, 'frontend_tree');
while($db->next_record()) {
	// sichtbar wenn:
	// online & nicht gesperrt
	// online, gesperrt aber frontendzugang und (frontendsehrecht oder eigenes sehrecht)
	$dedi_frontend['visible'] = (($db->f('visible') == 1 && $db->f('locked') == 0)
		|| ($db->f('visible') == 1 && $db->f('locked') == 1 && $perm->have_perm('area_frontend') && ($perm->have_perm(2, 'area_frontend', 0) || $perm->have_perm(1, 'cat', $db->f('idcat'))))) ? 1 : 0;
	$con_tree[$db->f('idcat')] = array('idcat'        =>$db->f('idcat'),
         				   'link'         =>$cfg_client['contentfile']."?lang=$lang&idcat=".$db->f('idcat'),
                                            'idcatlang'    =>$db->f('idcatlang'),
                                            'author'       =>$db->f('author'),
                                            'created'      =>$db->f('created'),
                                            'lastmodified' =>$db->f('lastmodified'),
                                            'parent'       =>$db->f('parent'),
                                            'visible'      =>$dedi_frontend['visible'],
                                            'idtplconf'    =>$db->f('idtplconf'),
                                            'description'  =>$db->f('description'),
                                            'name'         =>$db->f('name'));
	$tlo_tree[$db->f('parent')][$db->f('sortindex')] = $db->f('idcat');
}
unset($dedi_frontend['visible']);
tree_level_order('0', 'catlist');
if(is_array($con_tree)) {
	// Aufbau des Arrays $con_side
	// Abfrage Recht: Darf geschützte Seiten sehen
	$sql = "SELECT D.idcatside, D.idcat, D.sortindex, D.is_start, E.idside,
		IF ((F.online & 0x03) = 0x01 OR ((F.online & 0x02) = 0x02 AND (UNIX_TIMESTAMP(NOW()) BETWEEN F.start AND F.end)), 1 , 0) AS online,
		IF (((F.online & 0x04) = 0x00) ,'0' ,'1') AS locked,
		F.title, F.start, F.end, F.idsidelang, F.created, F.lastmodified, F.idtplconf
		FROM ".$dedi_db['cat_side']." AS D
                 LEFT JOIN ".$dedi_db['side']." AS E USING(idside)
                 LEFT JOIN ".$dedi_db['side_lang']." AS F USING(idside)
		WHERE F.idlang = '$lang'
		AND D.idcat IN (".implode(',', array_keys($con_tree)).")
		ORDER BY D.idcatside";
	$db->query($sql, 1, 'frontend_tree');
	while($db->next_record()) {
		// online wenn:
		// online & nicht gesperrt
		// online, gesperrt aber frontendzugang  und (frontendsehrecht oder eigenes sehrecht)
		$dedi_frontend['online'] = (($db->f('online') == 1 && $db->f('locked') == 0)
			|| ($db->f('online') == 1 && $db->f('locked') == 1 && $perm->have_perm('area_frontend') && ($perm->have_perm(2, 'area_frontend', 0) || $perm->have_perm(17, 'side', $db->f('idcatside'), $db->f('idcat'))))) ? 1 : 0;
		$con_side[$db->f('idcatside')] = array('link'               =>$cfg_client['contentfile']."?lang=$lang&idcatside=".$db->f('idcatside'),
                 				       'idcat'              =>$db->f('idcat'),
                                                        'sortindex'          =>$db->f('sortindex'),
                                                        'idside'             =>$db->f('idside'),
                                                        'name'               =>$db->f('title'),
                                                        'created'	    =>$db->f('created'),
                                                        'lastmodified'       =>$db->f('lastmodified'),
                                                        'online'             =>$dedi_frontend['online'],
                                                        'idsidelang'         =>$db->f('idsidelang'),
                                                        'is_start'           =>$db->f('is_start'),
                                                        'idtplconf'          =>$db->f('idtplconf'),
                                                        'user_protected'     =>$db->f('user_protected'));
	}
}
unset($dedi_frontend['online']);

// mod_rewrite initialisieren
require_once ($cfg_client['path'].'cms/inc/mod_rewrite.php');
modrewrite_path($code);

// idcatside suchen
if (!$idcatside) {
	if ($idcat) {
		$sql = "SELECT idcatside
			FROM ".$dedi_db['cat_side']."
			WHERE idcat = '$idcat'
			AND is_start = '1'
			LIMIT 0, 1";
	} else {
		$sql = "SELECT idcatside
			FROM ".$dedi_db['cat_side']." AS A
                         LEFT JOIN ".$dedi_db['cat']." AS B USING(idcat)
			WHERE is_start = '1'
			AND idclient = '$client'
			ORDER BY parent, B.sortindex
                         LIMIT 0, 1";
	}
	$db->query($sql);
	if ($db->next_record()) $idcatside = $db->f('idcatside');
	else frontend_errorpage($idcatside);
}

// get advanced sideinfos for this side
// idcatside prüfen, da der User auch in einer Kategorie sein kann, wo es noch keine seite
// und damit idcatside gibt.
// es gibt keine idsidelang, wenn der user nicht das recht hat, die seite zu sehen
if (!empty($idcatside) && ! empty($con_side[$idcatside]['idsidelang'])){
	$sql = "SELECT meta_author, meta_description, meta_keywords, meta_robots, meta_redirect,
		meta_redirect_url, summary, author, created, lastmodified
		FROM ".$dedi_db['side_lang']."
		WHERE idsidelang = '".$con_side[$idcatside]['idsidelang']."'";
	$db->query($sql);
	$db->next_record();
	$con_side[$idcatside]['meta_author'] = $db->f('meta_author');
	$con_side[$idcatside]['meta_description'] = $db->f('meta_description');
	$con_side[$idcatside]['meta_keywords'] = $db->f('meta_keywords');
	$con_side[$idcatside]['meta_robots'] = $db->f('meta_robots');
	$con_side[$idcatside]['meta_redirect'] = $db->f('meta_redirect');
	$con_side[$idcatside]['meta_redirect_url'] = $db->f('meta_redirect_url');
	$con_side[$idcatside]['summary'] = $db->f('summary');
	$con_side[$idcatside]['author'] = $db->f('author');
	$con_side[$idcatside]['created'] = $db->f('created');
	$con_side[$idcatside]['lastmodified'] = $db->f('lastmodified');
}

// $idcat und $idside ermitteln
if (empty($idcat)) $idcat  = $con_side[$idcatside]['idcat'];
if (empty($idside)) $idside = $con_side[$idcatside]['idside'];

// Ausgabe beenden, wenn Kategorie oder Seite nicht online
if ($con_side[$idcatside]['online'] != 1 || $con_tree[$idcat]['visible'] != 1) frontend_errorpage($idcatside);

// Inhalt aus der Datenbank suchen
if (!$code && ( $auth->auth['uid'] != 'nobody' |	($con_tree[$idcat]['visible'] == '1' && !empty($con_side[$idcatside]['online']) && $con_side[$idcatside]['online'] != '0'))) {
	if (!empty($con_tree[$con_side[$idcatside]['idcat']]['idcat'])) {
		$sql = "SELECT code, changed
			FROM ".$dedi_db['code']."
			WHERE idcatside = '$idcatside'
			AND idlang = '$lang'";
		$db->query($sql);
		$db->next_record();
		$code = $db->f('code');
		$code_changed = $db->f('changed');
		if ($code_changed == '' || $code_changed == '1') {
			// Seite generieren weil keine Daten gefunden oder Daten verändert
			include ($dedi_path.'inc/inc.generate_code.php');

			// Delete Content Cache
			$db->delete_cache('frontend_content');

			// schauen, ob sich deditags im dynamischen php (<DEDIPHP>) befinden, wenn ja, nicht cachen
			$dynamic = strpos ($code, 'echo type_output_');
			if (is_int($dynamic)) $cfg_client['cache'] = '0';

			// Seite in die 'code'-Tabelle schreiben
			if ($cfg_client['cache'] == '1') {
				$sql  = "SELECT *
					FROM ".$dedi_db['code']."
					WHERE idcatside = '$idcatside'
					AND idlang = '$lang'";
				$db->query($sql);
				if ($db->next_record()) {
					// Update vorhandener Seite
					$sql = "UPDATE ".$dedi_db['code']."
						SET code = '".dedi_addslashes($code)."', changed = '0'
						WHERE idcatside = '$idcatside'
						AND idlang = '$lang'";
				} else {
					// Insert neue Seite
					$sql = "INSERT INTO ".$dedi_db['code']." (idlang, idcatside, code, changed)
						VALUES ('$lang', '$idcatside', '".dedi_addslashes($code)."', '0')";
				}
				$db->query($sql);
			}
		}
	}
}

// Seite ausgeben
if ($code) {
	// Seite weiterleiten?
	if ($con_side[$idcatside]['meta_redirect'] == '1' && $con_side[$idcatside]['meta_redirect_url'] != '') {
		header ('Status: 302 Moved Temporarily');
		if (is_numeric($con_side[$idcatside]['meta_redirect_url'])) {
                 	$con_side[$idcatside]['meta_redirect_url'] = $con_side[$con_side[$idcatside]['meta_redirect_url']]['link'];
		}
		header ('Location: '.str_replace('&amp;', '&', modrewrite_replace($con_side[$idcatside]['meta_redirect_url'])));
	} else {
		eval('?>'.$code);
		$code = ob_get_contents ();
		ob_end_clean ();
		ob_start();
		echo modrewrite_replace($code);
	}
} else frontend_errorpage();
?>